如何在 swiftUI 中创建循环心跳动画?

Jus*_*n A 4 swiftui

我正在尝试创建一个动画,其中有一个小心脏图标在跳动。我有两个图像,我相信足以创建效果,但我不知道如何创建这个动画效果。我尝试了几种方法,但似乎都不起作用。

您能提供的任何帮助将不胜感激。

这是我到目前为止所拥有的:

@State var show : Bool = false
    var body: some View {
        VStack(alignment: .trailing){
            ZStack{
                BlackView()
                if(show){
                    Image("heartOrgan1")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 50, height:50)
                        .hidden()
                        
                    Image("heartOrgan")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 50, height: 50)
                    
                } else {
                    Image("heartOrgan1")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 50, height: 50)
                        
                    Image("heartOrgan")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 50, height: 50)
                        .hidden()
                }
            }
            .onAppear(){
                
                withAnimation { self.show.toggle()}
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

总体思路是在代表心脏跳动的两个心脏图像之间循环切换。我对使用这些特殊的心脏图像很感兴趣,因为它们看起来像真正的心脏,我喜欢这一点。

Jam*_*jon 10

为此,您不一定需要两张图像。您可以使用一张图像并对其应用缩放效果。放大一张图像并为其添加延迟。然后让它重复。

例子:

@State private var animationAmount: CGFloat = 1

var body: some View {
    ZStack {
        Color.black

        Image(systemName: "heart.fill")
            .resizable()
            .frame(width: 50, height: 50)
            .foregroundColor(.red)
            .scaleEffect(animationAmount)
            .animation(
                .linear(duration: 0.1)
                    .delay(0.2)
                    .repeatForever(autoreverses: true),
                value: animationAmount)
            .onAppear {
                animationAmount = 1.2
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以更改内部的小数值delay()以获得不同的心跳。心跳看起来与 0.1 - 0.4 之间的延迟一致。