如何使用 SwiftUI 为一系列图像设置动画?

Meh*_*hdi 6 xcode animation ios swift swiftui

如何使用 SwiftUI 框架为一系列图像(比如 Frame-1.png 到 Frame-6)设置动画?

我试过创建一个“图像”数组。然后我将 UIImage.animatedImage(with: images, duration: 1.0) 方法分配给一个名为“animatedImage”的变量,最后我在“ContentView.swift”的“body”中尝试了 Image(uiImage:animatedImage)


var images: [UIImage]! = [UIImage(named: "Sequence/frame-1")!,
                          UIImage(named: "Sequence/frame-2")!,
                          UIImage(named: "Sequence/frame-3")!,
                          UIImage(named: "Sequence/frame-4")!,
                          UIImage(named: "Sequence/frame-5")!,
                          UIImage(named: "Sequence/frame-6")!
]

let animatedImage : UIImage! = UIImage.animatedImage(with: images, duration: 1.0)

//////Then in the ContentView.swift I've tried this code:

struct ContentView : View {
    var body: some View {

        Image(uiImage: animatedImage)

    }
}

Run Code Online (Sandbox Code Playgroud)

当我运行程序时,它只显示第一帧,但我期望帧的动画

Nun*_*ves 7

接受的答案非常有效,因为 bhagyash ingale 提到了不幸的问题,这使得它很难使用。如果Image可以通过协议或其他方式重用的特定方法,那将会很有用。我有一个非常差的,也许是巨大的大炮来解决这个问题,也许时间会更容易,但现在......

class LoadingTimer {

    let publisher = Timer.publish(every: 0.1, on: .main, in: .default)
    private var timerCancellable: Cancellable?

    func start() {
        self.timerCancellable = publisher.connect()
    }

    func cancel() {
        self.timerCancellable?.cancel()
    }
}
Run Code Online (Sandbox Code Playgroud)
struct LoadingView: View {

    @State private var index = 0

    private let images = (0...7).map { UIImage(named: "Image-\($0).jpg")! }
    private var timer = LoadingTimer()

    var body: some View {

        return Image(uiImage: images[index])
            .resizable()
            .frame(width: 100, height: 100, alignment: .center)
            .onReceive(
                timer.publisher,
                perform: { _ in
                    self.index = self.index + 1
                    if self.index >= 7 { self.index = 0 }
                }
            )
            .onAppear { self.timer.start() }
            .onDisappear { self.timer.cancel() }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这样,但它可以完成工作并依赖于Image.

  • 您需要导入联合收割机。 (2认同)

nig*_*ill 7

没有合并的版本

import SwiftUI

struct AnimatingImage: View {
    let images: [Image]

    @ObservedObject private var counter = Counter(interval: 0.05)
        
    var body: some View {
        images[counter.value % images.count]
    }
}

private class Counter: ObservableObject {
    private var timer: Timer?

    @Published var value: Int = 0
    
    init(interval: Double) {
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in self.value += 1 }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以使用它

struct LoadingView: View {
    private let images = (1...20).map { String(format: "i_%02d", $0) }.map { Image($0) }
    
    var body: some View {
        AnimatingImage(images: images)
    }
}
Run Code Online (Sandbox Code Playgroud)