Objective c 不显示图像的关键帧动画
我使用iOS 8.1设置了一个非常简单的单视图应用程序(Swift)。我在主视图控制器视图中添加了一个UIImageView。我正在尝试使用CAKeyframeAnimation为一系列图像设置动画。我最初使用的是UIImageView animationImages属性,该属性工作正常,但我需要能够准确地知道动画何时完成,从而移动到CAKeyframeAnimation 我的代码如下:Objective c 不显示图像的关键帧动画,objective-c,animation,swift,uiimageview,cakeyframeanimation,Objective C,Animation,Swift,Uiimageview,Cakeyframeanimation,我使用iOS 8.1设置了一个非常简单的单视图应用程序(Swift)。我在主视图控制器视图中添加了一个UIImageView。我正在尝试使用CAKeyframeAnimation为一系列图像设置动画。我最初使用的是UIImageView animationImages属性,该属性工作正常,但我需要能够准确地知道动画何时完成,从而移动到CAKeyframeAnimation 我的代码如下: class ViewController: UIViewController { @IBOutlet w
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
属性必须设置为CGImage,而不是UIImage。相比之下,您的animationImages
包含UIImages,而不是CGImages
因此,您需要将UIImage数组转换为CGImage数组。此外,您试图将此数组传递给Objective-C,其中NSArray必须只包含对象;由于CGImage在Objective-C的头脑中不是一个对象,所以您需要将它们中的每一个都转换为AnyObject。这就是我的
map
调用所做的。这不是一个确切的答案,但请注意,在viewDidLoad
中制作动画是没有意义的。当时发生的一切是视图已加载到视图控制器中。该视图尚未在界面中。在viewDidLoad
时没有什么可看的。感谢Matt的更正。在我最初的代码库中,我确实从ViewDidEmbeen调用了它,但在组合简单的测试项目时,我不幸没有考虑正确的放置位置。没问题——只是确保您知道其中的差异。你是!有关这种“精灵”图像动画的工作示例,请参阅我的书中的代码:谢谢Matt。回答得很好,也谢谢你的书的链接,它将来会派上用场的。非常感谢你澄清了这个谜题的CGImage部分。我花了几个小时试图解决这个问题+1.