如何在 SwiftUI 中为动画图像设置延迟?

How to set a delay for the animated Image in SwiftUI?

我想让动物以不同的延迟眨眼Int.random(in: 1..<9)

问题是:

UIView 动画和异步线程延迟的解决方案...但是 UIImage.animatedImage 有什么方法可以在眨眼之间进行延迟吗?

如果根本没有方法 - 我该如何解决我的问题?

The code:

所有动画的文件:

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

我在 ContentViewbody

中使用它
            VStack {
                    AnimalAnimation(animalImages: $animal1Array, size: $animal1Size)
            }

图片:

animalImages = [UIImage(named: "eyes-open"),UIImage(named: "eyes-closed")]

为什么不在数组中再次添加相同的图像,这样 "looks like" 会有延迟?

这里是 SwiftUI 的唯一变体。使用 Xcode 11.4 / iOS 13.4 进行测试。 (Sizes/frames如果需要可以配置,demo无所谓)

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