UIImageView中的iOS 11动画gif显示 [英] iOS 11 animated gif display in UIImageView

查看:554
本文介绍了UIImageView中的iOS 11动画gif显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为iOS 11应该最终带来对GIF动画的本机支持?但我尝试了这个,我没有看到任何动画:

I thought iOS 11 was supposed to bring, at long last, native support for animated gifs? But I tried this, and I didn't see any animation:

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
}

这应该如何工作?

推荐答案

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

iOS 11 does bring a native understanding of animated gifs, but that understanding, infuriatingly, is not built into UIImageView. It is still up to you to translate the animated gif into a sequence of UIImages. Apple now provides sample code, in terms of the ImageIO framework:

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

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

That code implements an AnimatedImage class, which is essentially a collection of CGImages extracted from the original animated gif. Thus, using that class, we can display and animate the animated gif in a UIImageView as follows:

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()
}

这篇关于UIImageView中的iOS 11动画gif显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆