UIImageView中的iOS 11动画gif显示

时间:2017-08-17 21:48:22

标签: ios animation uiimageview animated-gif ios11

我认为iOS 11本来应该带来对GIF动画的原生支持?但我试过这个,我没有看到任何动画:

let im = UIImage(named:"wireframe.gif")!
let iv = UIImageView(image:im)
iv.animationImages = [im] // didn't help
iv.frame.origin = CGPoint(0,100)
iv.frame.size = im.size
self.view.addSubview(iv)
delay(2) {
    iv.startAnimating() // nope
}

这应该如何运作?

2 个答案:

答案 0 :(得分:15)

iOS 11确实带来了对GIF动画的本地理解,但这种理解,令人愤怒,并没有内置到UIImageView中。仍然需要将动画gif转换为一系列UIImages。 Apple现在根据ImageIO框架提供示例代码:

https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/Listings/Shared_AnimatedImage_swift.html

该代码实现了一个AnimatedImage类,它基本上是从原始动画gif中提取的CGImages的集合。因此,使用该类,我们可以在UIImageView中显示动画gif并为其设置动画,如下所示:

let url = Bundle.main.url(forResource: "wireframe", withExtension: "gif")!
let anim = AnimatedImage(url: url)!
var arr = [CGImage]()
for ix in 0..<anim.frameCount {
    arr.append(anim.imageAtIndex(index: ix)!)
}
var arr2 = arr.map {UIImage(cgImage:$0)}
let iv = UIImageView()
iv.animationImages = arr2
iv.animationDuration = anim.duration
iv.frame.origin = CGPoint(0,100)
iv.frame.size = arr2[0].size
self.view.addSubview(iv)
delay(2) {
    iv.startAnimating()
}

答案 1 :(得分:1)

不幸的是,GIF的帧间时序可能因帧而异,因此使用ImageIO加载帧然后将它们设置为UIImageView上的animatedImages的答案需要正确提取时序并将其考虑在内。< / p>

我推荐使用Flipboard的FLAnimatedImage,它可以正确处理GIF。 https://github.com/Flipboard/FLAnimatedImage

相关问题