Swift + UIImageView:在两个动画帧序列之间切换?

时间:2019-04-30 14:29:38

标签: swift animation uiimageview uiimage frames

动画代码示例:

func startAnimation(index: Int) {
var jumpImages = ["Jump_1","Jump_2","Jump_3","Jump_4","Jump_5","Jump_6","Jump_7","Jump_8","Jump_9","Jump_10"]
if index == 1 {
     jumpImages = ["Jump_11","Jump_21","Jump_31","Jump_41","Jump_51","Jump_61","Jump_71","Jump_81","Jump_91","Jump_101"]
}
    var images = [UIImage]()
    for image in jumpImages{
        images.append(UIImage(named: image)!)
    }
    self.imageView.frame.origin.y = self.imageView.frame.origin.y + 100.0
    self.imageView.animationImages = images
    self.imageView.animationDuration = 2.0
    self.imageView.animationRepeatCount = 1
    self.imageView.startAnimating()
}
startAnimation(index: 0)
...
startAnimation(index: 1)

注意:两个startAnimation调用都在主线程中,但不在同一运行循环中。

就我而言,我想将jumpImages更改为另一组图像。我应该取消上一个动画,然后开始新的动画,但是好像我以jumpImages顺序设置了最后一个图像。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

好的,我想我现在已经了解了您的问题-从您的陈述中,“ [...],但看起来好像我将最后一个图像设置为jumpImages序列,”您的意思是当您调用 startAnimation(index:1)时,您只会看到index 0动画的最后一帧,而没有index 1动画。

假设这是正确的,那么您遇到的问题就是比赛情况。

当您调用 startAnimation(),然后第二次使用索引1时,第一个动画可能正在进行或可能仍未进行。

解决方案是在更改所有图像并开始新动画之前调用 self.imageView.stopAnimating()。最佳做法是在调用 imageView.isAnimating 标志之前。像这样:

func startAnimation(index: Int) {
    var jumpImages = ["Jump_1","Jump_2","Jump_3","Jump_4","Jump_5","Jump_6","Jump_7","Jump_8","Jump_9","Jump_10"]
    if index == 1 {
         jumpImages = ["Jump_11","Jump_21","Jump_31","Jump_41","Jump_51","Jump_61","Jump_71","Jump_81","Jump_91","Jump_101"]
    }
    var images = [UIImage]()
    for image in jumpImages{
        images.append(UIImage(named: image)!)
    }

    if self.imageView.isAnimating {
        self.imageView.stopAnimating()
    }
    self.imageView.frame.origin.y = self.imageView.frame.origin.y + 100.0
    self.imageView.animationImages = images
    self.imageView.animationDuration = 2.0
    self.imageView.animationRepeatCount = 1
    self.imageView.startAnimating()
}
startAnimation(index: 0)
...
startAnimation(index: 1)

此外,由于您在函数中,而不是在闭包中,因此可以删除对 self。的所有引用。这会使事情变得更短:

func startAnimation(index: Int) {
    var jumpImages = ["Jump_1","Jump_2","Jump_3","Jump_4","Jump_5","Jump_6","Jump_7","Jump_8","Jump_9","Jump_10"]
    if index == 1 {
         jumpImages = ["Jump_11","Jump_21","Jump_31","Jump_41","Jump_51","Jump_61","Jump_71","Jump_81","Jump_91","Jump_101"]
    }
    var images = [UIImage]()
    for image in jumpImages{
        images.append(UIImage(named: image)!)
    }

    if imageView.isAnimating {
        imageView.stopAnimating()
    }
    imageView.frame.origin.y = imageView.frame.origin.y + 100.0
    imageView.animationImages = images
    imageView.animationDuration = 2.0
    imageView.animationRepeatCount = 1
    imageView.startAnimating()
}
startAnimation(index: 0)
...
startAnimation(index: 1)