且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 swiftUI 创建平滑的颜色变化动画?(有问题的例子)

更新时间:2023-10-27 21:14:40

这是一个可能的方法的演示 - 只需在文本和不透明背景之间使用一些形状(在这种情况下为圆形)并根据状态移动它.

Here is a demo of possible approach - just use some shape (circle in this case) between text and opaque background and move it depending on state.

已准备好 Xcode 12.4/iOS 14.4

Prepared with Xcode 12.4 / iOS 14.4

注意:您可以只使用点击手势而不是按钮并调整所有参数和颜色,但总体上思路保持不变

struct DemoView: View {
    @State private var playing = false
    var body: some View {
        Button(action: { playing.toggle() }) {
            HStack{
                Image(systemName: playing ? "pause" : "play")
                Text(playing ? "STOP" : "PLAY")
                    .bold()
            }
            .background(
                Circle().fill(Color.purple)
                    .frame(width: 160, height: 160, alignment: .leading)
                    .blur(radius: 3)
                    .offset(x: playing ? 0 : -160, y: -40)
                    .animation(.easeInOut(duration: 1), value: playing)
            )
            .padding()
            .foregroundColor(.white)
            .background(Color.green)
            .cornerRadius(25)
            .clipped()
            .shadow(radius: 20)
        }
    }
}