具有渐变填充的矩形并尝试为颜色变化设置动画。
...
Rectangle()
.fill(LinearGradient(
gradient: .init(stops: [Gradient.Stop(color: myColor, location: 0.0), Gradient.Stop(color: .blue, location: 1.0)]),
startPoint: .init(x: 0.5, y: startPoint),
endPoint: .init(x: 0.5, y: 1-startPoint)
))
.animation(Animation.easeIn(duration: 2))
...
Run Code Online (Sandbox Code Playgroud)
虽然起点的变化很好地动画; 颜色变化根本没有动画,只是“切换”
任何提示?
Pav*_*Zak 13
因此,如果有人会为此而苦苦挣扎,我当前的解决方案是在 ZStack 中有两个渐变并为顶部的不透明度设置动画
这是一个粗略的例子,代码肯定可以写得更好:
///helper extension to get some random Color
extension Color {
static func random()->Color {
let r = Double.random(in: 0 ... 1)
let g = Double.random(in: 0 ... 1)
let b = Double.random(in: 0 ... 1)
return Color(red: r, green: g, blue: b)
}
}
struct AnimatableGradientView: View {
@State private var gradientA: [Color] = [.white, .red]
@State private var gradientB: [Color] = [.white, .blue]
@State private var firstPlane: Bool = true
func setGradient(gradient: [Color]) {
if firstPlane {
gradientB = gradient
}
else {
gradientA = gradient
}
firstPlane = !firstPlane
}
var body: some View {
ZStack {
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: self.gradientA), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 1, y: 1)))
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: self.gradientB), startPoint: UnitPoint(x: 0, y: 0), endPoint: UnitPoint(x: 1, y: 1)))
.opacity(self.firstPlane ? 0 : 1)
///this button just demonstrates the solution
Button(action:{
withAnimation(.spring()) {
self.setGradient(gradient: [Color.random(), Color.random()])
}
})
{
Text("Change gradient")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:*最后我探索了几种动画渐变填充的方法,并在此处总结:https : //izakpavel.github.io/development/2019/09/30/animating-gradients-swiftui.html *
| 归档时间: |
|
| 查看次数: |
2749 次 |
| 最近记录: |