我想实现一个动画背景,在 SwiftUI 中对一堆图像进行淡入淡出。
我已经使用以下代码片段设法使一组颜色在它们之间很好地交叉淡入淡出,但是如果我用一组图像替换颜色数组,则相同的方法不起作用。图像被替换,但没有动画。然而 Color 和 Image 都属于 some View 类型,对吗?
以下工作:
struct ImageBackgroundView: View {
@State private var index = 0
private let colors:[Color] = [.red, .blue, .green, .orange, .pink, .black]
private let timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect()
var body: some View {
colors[self.index]
.animation(.easeInOut(duration: 1))
.onReceive(timer) { _ in
print(self.index)
self.index += 1
if self.index > 5 { self.index = 0 }
}
}
但是,如果我用 [Images] 类型的数组替换 [Color] 数组,如下所示,图像会转换,但交叉淡入淡出似乎不起作用:
struct ImageBackgroundView: View {
@State private var index = 0
private let images = (1...8).map { Image("background\($0)") }
private let timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect()
var body: some View {
images[self.index]
.animation(.easeInOut(duration: 1))
.onReceive(timer) { _ in
print(self.index)
self.index += 1
if self.index > 5 { self.index = 0 }
}
}
任何人都可以解释为什么会这样吗?目前这只是 SwiftUI 中的一个错误吗?
我在以前的应用程序中使用各种 addSubview 调用实现了类似的效果,这些调用为覆盖 View 的不透明度设置动画——在这个勇敢的新 SwiftUI 世界中,我们不需要摆弄各种东西,对吧?
最佳答案
这很有趣,它让我思考。
您可以使用标志,例如 show
.还有一个 ZStack
持有您的 image
目的。
然后使用 transition
结合 animation
你想要的image
.
但是,只有在 show
时才这样做是 true
.
附上 .onReceive
事件到 ZStack
而不是您的 image
.在这种情况下,切换标志 show
.
@State private var index = 0
@State private var show = true
private let images = (1...8).map { Image("background\($0)") }
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
ZStack {
if self.show {
images[self.index]
.transition(AnyTransition.opacity.animation(.easeInOut(duration: 1.0)))
}
}.onReceive(timer) { _ in
print(self.index)
self.index += 1
self.show.toggle()
if self.index > 4 { self.index = 0 }
}
}
瞧!
另外,据我所知,
Color
不是 View
.A Color is a late-binding token: SwiftUI only resolves it to a concrete value just before using it in a given environment.
引用:https://developer.apple.com/documentation/swiftui/color
关于ios - SwiftUI 中的淡入淡出图像似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60627957/