gpt4 book ai didi

swiftui - swiftUI 中的动画渐变填充

转载 作者:行者123 更新时间:2023-12-03 18:29:26 32 4
gpt4 key购买 nike

具有渐变填充的矩形并尝试为颜色变化设置动画。

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

虽然起点的变化很好地动画;颜色变化根本没有动画,只是“切换”

任何提示?

最佳答案

因此,如果有人会为此而苦苦挣扎,我目前的解决方案是 在 ZStack 中有两个渐变和顶部的动画不透明度

Example gif

这是一个粗略的例子,代码肯定可以写得更好:

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

更新 : *最后我探索了几种动画渐变填充的方法,并在此总结: https://izakpavel.github.io/development/2019/09/30/animating-gradients-swiftui.html *

关于swiftui - swiftUI 中的动画渐变填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57576659/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com