Swift UIimageView:在两个动画框架序列之间切换



动画代码的示例:

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序列中设置最后一个图像。

如何解决此问题?

好吧,我想我现在已经了解了您的问题 - 从您的陈述中,","我认为您的意思是,当您调用 startAnimation(index:1(时,您只是看到索引0动画的最后帧,而没有索引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)

最新更新