如何在SwiftUI中实现晃动效果?

5
我想要制作一个带有偏移的抖动效果,希望在开始时偏移量为零,在30.0和-30.0之间抖动,覆盖这些偏移量:-30.0、0.0、30.0。
但是在编码中我不能有这三个选项,只有两个选项,我的目标是从0.0开始到30.0,然后到-30.0,最后结束时回到0.0。
struct ContentView: View {
    @State private var start: Bool = false
    var body: some View {

        Image(systemName: "exclamationmark.triangle")
            .font(Font.system(size: 50))
            .offset(x: start ? 30.0 : -30.0)
            .padding()
            .animation(Animation.spring(response: 0.2, dampingFraction: 0.2, blendDuration: 0.2), value: start)
        
        Button("Shake") {
            start.toggle()
        }
    }
}

1
这个回答解决了你的问题吗?https://stackoverflow.com/a/60154727/12299030 - Asperi
我认为在那个链接中,sin函数是最重要的,这是非常好的方法。我相信以某种方式动画化sin值可以实现平滑动画效果。 - ios coder
1
请查看此链接,它可能会对您有所帮助:https://www.objc.io/blog/2019/10/01/swiftui-shake-animation/ - Jayachandra A
1个回答

10

您可以使用显式动画来替代隐式动画,然后在按钮中首先通过偏移量进行无动画位移,再通过动画进行回位:

struct ContentView: View {
    @State private var start: Bool = false
    var body: some View {
        
        VStack {
            Image(systemName: "exclamationmark.triangle")
                .font(Font.system(size: 50))
                .offset(x: start ? 30 : 0)
                .padding()
            
            Button("Shake") {
                start = true
                withAnimation(Animation.spring(response: 0.2, dampingFraction: 0.2, blendDuration: 0.2)) {
                    start = false
                }
            }
        }
    }
}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接