我想让动物以不同的延迟眨眼Int.random(in: 1..<9)
问题是:
有UIView
动画和异步线程延迟的解决方案...但是UIImage.animatedImage
是否有任何方法可以在眨眼之间进行延迟?
如果根本没有方法-我该如何解决我的问题?
代码:
所有动画的文件:
import SwiftUI
struct AnimalAnimation: UIViewRepresentable {
@Binding var animalImages: [UIImage?]
@Binding var size: CGRect
func makeUIView(context: Self.Context) -> UIView {
let someView = UIView(frame: CGRect(x: size.minX, y: size.minY , width: size.width, height: size.height))
let someImage = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let animated = UIImage.animatedImage(with: animalImages as! [UIImage], duration: 0.9)!
someImage.clipsToBounds = true
someImage.autoresizesSubviews = true
someImage.contentMode = UIView.ContentMode.scaleAspectFit
someImage.image = animated
someView.addSubview(someImage)
return someView
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<AnimalAnimation>) {
}
}
我正在ContentView
的{{1}}
body
图像:
VStack {
AnimalAnimation(animalImages: $animal1Array, size: $animal1Size)
}
答案 0 :(得分:3)
这是SwiftUI的唯一变体。已通过Xcode 11.4 / iOS 13.4测试。 (如果需要,可以配置尺寸/框架,演示无关紧要
struct EyesBlinkView: View {
enum EyesState: String {
case open = "eyes-open"
case closed = "eyes-closed"
}
@State private var eyesState = EyesState.open
var body: some View {
Image(eyesState.rawValue).resizable().scaledToFit()
.onAppear { self.blink() }
}
private func blink() {
self.eyesState = .closed
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
self.eyesState = .open
DispatchQueue.main.asyncAfter(deadline:
DispatchTime.now().advanced(by: .seconds(Int.random(in: 1..<9)))) {
self.blink()
}
}
}
}
答案 1 :(得分:0)
为什么不只是在阵列中再次添加相同的图像,以使其“看起来”像是一个延迟?