我已经使用 iOS 8.1 设置了一个非常简单的单 View 应用程序(在 Swift 中)。我在主视图 Controller View 中添加了一个 UIImageView。我正在尝试使用 CAKeyframeAnimation 为一系列图像设置动画。我最初使用的是 UIImageView animationImages 属性,它运行良好,但我需要能够准确地知道动画何时结束,因此移动到 CAKeyframeAnimation。
我的代码如下:
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var animation : CAKeyframeAnimation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let animationImages:[AnyObject] = [UIImage(named: "image-1")!, UIImage(named: "image-2")!, UIImage(named: "image-3")!, UIImage(named: "image-4")!]
animation = CAKeyframeAnimation(keyPath: "contents")
animation.calculationMode = kCAAnimationDiscrete
animation.duration = 25
animation.values = animationImages
animation.repeatCount = 25
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
self.imageView.layer.addAnimation(animation, forKey: "contents")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
问题是动画不显示任何图像,我只收到一个空白屏幕。上面的代码中有什么我遗漏的吗?如何让动画显示?
最佳答案
这条线永远行不通:
animation.values = animationImages
将其更改为:
animation.values = animationImages.map {$0.CGImage as AnyObject}
原因是您正在尝试为该层的 "contents"
键设置动画。但那是 contents
属性。但是 contents
属性必须设置为 CGImage,而不是 UIImage。相比之下,您的 animationImages
包含 UIImages,而不是 CGImages。
因此,您需要将 UIImage 数组转换为 CGImage 数组。此外,您试图将此数组传递给 Objective-C,其中 NSArray 必须仅包含对象;由于 CGImage 不是 Objective-C 心目中的对象,因此您需要将它们中的每一个都转换为 AnyObject。这就是我的 map
调用所做的。
关于objective-c - Swift CAKeyframe 动画不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27995478/