如何使用 swiftUI 创建平滑的颜色变化动画?(有问题的例子) [英] How can I create a smooth colour change animation using swiftUI? (Example in question)

查看:28
本文介绍了如何使用 swiftUI 创建平滑的颜色变化动画?(有问题的例子)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个播放/暂停按钮,按下时会发生变化.目前它只是淡入淡出,但我希望它执行一个看起来新颜色流过旧颜色的动画.

I have a play/pause button that changes when pressed. At the moment it just fades in and out but I would like it to perform a animation that looks like the new colour is flowing over the old one.

这是我目前所拥有的:

if(meditationViewModel.timerIsRunning){
    HStack{
        Image(systemName: "pause")
        Text("STOP")
            .bold()
     }
      .padding()
      .foregroundColor(.white)
      .background(Color.red)
      .cornerRadius(25)
      .shadow(radius: 20)
}else{
    HStack{
        Image(systemName: "play")
        Text("PLAY")
            .bold()
    }
     .padding()
     .foregroundColor(.white)
     .background(Color.green)
     .cornerRadius(25)
}

meditationViewModel.timerIsRunning 的变化发生在别处.

推荐答案

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

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)
        }
    }
}

这篇关于如何使用 swiftUI 创建平滑的颜色变化动画?(有问题的例子)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆