我使用iOS 8.1建立了一个非常简单的单一视图应用程序(在Swift中)。我在主视图控制器视图中添加了一个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.
}
}问题是动画不显示任何图像,我只收到一个空白屏幕。我在上面的代码中遗漏了什么吗?怎样才能让动画显示出来?
发布于 2015-01-17 02:42:37
这句话永远不会奏效:
animation.values = animationImages改为:
animation.values = animationImages.map {$0.CGImage as AnyObject}原因是您正在尝试动画该层的"contents"键。但这是contents属性。但是contents属性必须设置为CGImage,而不是UIImage。相比之下,animationImages包含的是UIImages,而不是CGImages。
因此,需要将UIImage数组转换为CGImage数组。此外,您还试图将这个数组传递给object,其中NSArray必须只包含对象;而且由于CGImage在object中不是一个对象,所以需要将它们中的每一个转换为AnyObject。这就是我的map调用所做的。
https://stackoverflow.com/questions/27995478
复制相似问题