【问题标题】:Image moving in loop animation - Swift图像在循环动画中移动 - Swift
【发布时间】:2023-04-03 12:22:01
【问题描述】:

我在过去的 4 个月里一直在 swift 上工作,从 2 周开始就在这个启动画面上工作。屏幕中间有汽车,2 个图像(城市和地形)从右到左(RtoL)循环移动作为背景。检查以下从我的 android 应用程序中获取的 gif:

我只能移动背景 RtoL,但只能移动一次。我尝试了其他动画选项,但似乎都没有。您可以看到这些图像比实际屏幕宽得多,因此应该没有任何问题。在下面检查我的方法:

func animate(_ image: UIImageView) {
UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], 
animations: {image.center.x -= 10}, 
completion: {_ in self.animate(image)})}

我唯一的要求是像上面的 gif 那样移动图像 RtoL,在循环中没有间隙。

谢谢:)

【问题讨论】:

  • 如果这个 gif 是你想要的,为什么不使用它呢?只需从 gif 中获取图像并将它们添加到 UIImageView.animationImages。然后将animationDuration设置为你想要的,然后简单地调用imageView.StartAnimation。它会循环直到你调用 stopAnimation
  • 你的想法很好,但是具有这种质量的 gif 会使其尺寸变得非常大,我的应用无法承受。
  • 那么也许你必须在图像视图上加倍,这样当图像的右边缘到达右边缘 og 时,你可以将相同的图像(作为另一个实例)附加到第一个图像的末尾屏幕?

标签: ios iphone swift xcode


【解决方案1】:

所以就像你必须移动背景但想让它看起来像汽车在移动一样,所以对于这种情况: 您必须制作 3 个不同的 imageViews

  1. 建筑背景
  2. 树木背景
  3. 为汽车。

就像我创建了这个动画一样。

而您想要从 LToRRToL 移动的图像必须在图像视图上加倍,以便您可以附加相同的图像(作为另一个实例)当图像的右边缘到达屏幕的右边缘时到第一个结束

如下图所示。

并添加此代码用于动画目的。

func animateBackground() {

    // Animate background
    // cityImage is the visible image
    // cityImage2 is the hidden image

    UIView.animate(withDuration: 12.0, delay: 0.0, options: [.repeat, .curveLinear], animations: {
        self.cityImage.frame = self.cityImage.frame.offsetBy(dx: -1 * self.cityImage.frame.size.width, dy: 0.0)
        self.cityImage2.frame = self.cityImage2.frame.offsetBy(dx: -1 * self.cityImage2.frame.size.width, dy: 0.0)
    }, completion: nil)

}

【讨论】:

    【解决方案2】:

    似乎您只是将图像向左移动,很快图像将移出屏幕,您将无法看到它。尝试在每次动画迭代后将图像重新设置回其原始位置。你可以像这样使用 CGAffineTransform 来做到这一点:

    func animate(_ image: UIImageView) {
        UIView.animate(withDuration: 5, delay: 0, options: .curveLinear, animations: { 
            image.transform = CGAffineTransform(translationX: -100, y: 0)
        }) { (success: Bool) in
            image.transform = CGAffineTransform.identity
            animate(image)
        }
    }
    

    希望有帮助

    【讨论】:

    • 它没用 :( 实际上一次迭代是:屏幕左边缘的图像左端 --> 屏幕右边缘的图像右端。重新设置迭代没有帮助创建一个完美的循环。完成第一次迭代后“图像的左端应该在屏幕的右边缘”以使其完美循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多