【问题标题】:problem with image animation in viewDidAppear(), any advice?viewDidAppear() 中的图像动画问题,有什么建议吗?
【发布时间】:2020-03-30 21:40:10
【问题描述】:

我正在尝试创建一个滚动浏览一系列图像的动画。以下代码没有任何动画,只有该系列的最后一张图片出现在屏幕上。如何修复此动画?

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        imageSelection(score: 50)
    }
func imageSelection(score: Int) {
        var myScore = score
        if score < 10 {
            myScore = 1
        }
        else if score < 20 && score > 10 {
            myScore = 2
        }
        else if score < 30 && score > 20 {
            myScore = 3
        }
        else if score < 40 && score > 30 {
            myScore = 4
        }
        else if score < 50 && score > 40 {
            myScore = 5
        }
        else if score == 50 {
            myScore = 6
        }
        for i in 1...myScore{
            UIView.animate(withDuration: 0.5) {
                self.cookieImage.image = UIImage(named: "rewardsCookie\(i)")
                self.view.layoutIfNeeded()
            }
        }
    }

【问题讨论】:

  • 您没有为任何可动画属性设置动画,而是同时运行所有 myScore 非动画。
  • 另外,使用UIView 动画块是无法实现的。您必须使用CAAnimation 编写动画。请记住,layoutIfNeeded() 仅在约束发生变化时才进行动画处理,而您在此 sn-p 中没有动画(如果您正确设置约束,最多将动画图像大小更改)。如果您想要从一个图像到另一个图像的过渡动画(例如淡入淡出),您必须实现它们。
  • @matt 什么是动画属性?以及如何分别运行它们?
  • @VladRusu 你能回答我如何为此创建一个 CAAnimaiton 吗?
  • 动画视图属性在 UIView 文档中列出;没有任何关于 UIImageView 仅设置图像会导致任何类型的动画,您必须使用 CABasicAnimation 或类似的“从头开始”编写该动画

标签: ios swift xcode animation viewdidappear


【解决方案1】:

正如马特所说,您没有为任何可动画属性设置动画。您可以通过使用图层动画来实现您想要的效果。用以下代码替换您的 for 循环。

    var images = [CGImage]()
    for i in 1...myScore{
        images.append(UIImage(named: "rewardsCookie\(i)")!.cgImage!)
    }
    let animation = CAKeyframeAnimation(keyPath: "contents")
    animation.values = images
    let delay = 3.0 // in case you need to delay your animation
    animation.duration = 5.0 // change to the total duration (ex: 0.5 * myScore)
    animation.beginTime = CACurrentMediaTime() + delay
    self.cookieImage.layer.add(animation, forKey: nil)

请注意,对于图层动画,您实际上并没有看到 UIImageView,而是它的缓存版本。一旦动画完成并且原始图层再次显示,这将从屏幕上删除。因此,您将看到动画开始之前在cookieImageView 上可见的图像。为了持久化最后一张图片,在上面的代码后面加上下面这行

    self.cookieImage.image = UIImage(named: "rewardsCookie\(myScore)")

欲了解更多信息,请通过Apple's Documentation

【讨论】:

    【解决方案2】:

    您是否正在尝试制作“翻书”动画,让您在一系列图像之间翻转?最简单的方法是使用 UIImageView 动画。有关详细信息,请参阅 Xcode 中的 UIImageView 类参考(请参阅标题为“动画图像序列”的部分。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2015-08-03
      相关资源
      最近更新 更多