如何制作动画图像以在屏幕上连续移动?

CS0*_*521 1 swiftui

这段代码显示了我试图实现的一般行为,但如何才能使其连续,使图像没有明显的结尾,没有空白间隙和平滑过渡?并且 - 有没有更好的方法来做到这一点???

谢谢!

import SwiftUI

struct ContentView: View {
    @State private var xVal: CGFloat = 0.0
    @State private var timer = Timer.publish(every: 0.05, on: .main, in: .common).autoconnect()

    var body: some View {
        ZStack {
            Image("game_background_2")  //image attached
                .aspectRatio(contentMode: .fit)
                .offset(x: xVal, y: 0)
                .transition(.slide)
                .padding()
                .onReceive(timer) {_ in
                    xVal += 2
                    if xVal == 800 { xVal = 0 }
                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

nic*_*rno 5

这是一个可行的简单方法。首先使用 GeometryReader 设置屏幕的框架。然后添加一个HStack,里面有2张图片。第一个图像是全尺寸,第二个图像仅限于屏幕宽度。最后,设置 HStack 的动画,使其从屏幕框架的 .trailing 移动到 .leading 边缘。我们设置动画 .repeatForever 以便它继续循环和 autoReverses: false 以便它重新启动。然而,当它重新启动时,它应该是无缝的,因为重新启动位置与第二个图像相同。

struct ImageBackgroundView: View {
    
    @State var animate: Bool = false
    let animation: Animation = Animation.linear(duration: 10.0).repeatForever(autoreverses: false)
    
    var body: some View {
        GeometryReader { geo in
            HStack(spacing: -1) {
                Image("game_background_2")
                    .aspectRatio(contentMode: .fit)

                Image("game_background_2")
                    .aspectRatio(contentMode: .fit)
                    .frame(width: geo.size.width, alignment: .leading)
            }
            .frame(width: geo.size.width, height: geo.size.height,
                   alignment: animate ? .trailing : .leading)
        }
        .ignoresSafeArea()
        .onAppear {
            withAnimation(animation) {
                animate.toggle()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)