You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SwiftUI复刻UIKit中的弹簧脉冲动画效果?

SwiftUI复刻UIKit脉冲动画实现思路求助

我想在SwiftUI里用.spring动画复刻之前UIKit里实现的点击脉冲效果。UIKit代码实现的效果是:点击ImageView时,先立即将图片每个角落缩进20点(整体缩小40点),再通过0.25秒的弹簧阻尼动画恢复到原尺寸,动画效果如下:

动画效果展示

对应的UIKit实现代码:

@IBAction func imageTapped(_ sender: UITapGestureRecognizer) {
    let originalImageFrame = imageView.frame
    let imageWidthShrink: CGFloat = 20
    let imageHeightShrink: CGFloat = 20
    let smallerImageFrame = CGRect(
        x: imageView.frame.origin.x + imageWidthShrink,
        y: imageView.frame.origin.y + imageHeightShrink,
        width: imageView.frame.width - (imageWidthShrink * 2),
        height: imageView.frame.height - (imageHeightShrink * 2))
    imageView.frame = smallerImageFrame
    playSound(name: "punchSound")
    UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10.0, options: [], animations: {
        self.imageView.frame = originalImageFrame
    })
}

我现在在SwiftUI里尝试通过点击触发.spring动画,但当前代码只能在1.0和1.1的缩放比例间切换,无法实现「先立即缩小到目标尺寸、再通过弹簧动画恢复原尺寸」的效果,希望能得到技术思路。

当前SwiftUI代码:

@State private var animateImage = false
...

selectedImage
    .resizable()
    .scaledToFit()
    .scaleEffect(animateImage ? 1.0 : 1.1)
    .animation(.spring(response: 0.3, dampingFraction: 0.3), value: animateImage)
    .onTapGesture {
        print("You tapped me!")
        playSound(name: "punchSound")
        animateImage.toggle()
    }

内容的提问来源于stack exchange,提问作者Gallaugher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:27:29