UIImageView 中的 iOS 11 动画 gif 显示 [英] iOS 11 animated gif display in UIImageView
问题描述
我认为 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:
该代码实现了一个 AnimatedImage 类,它本质上是从原始动画 gif 中提取的 CGImage 的集合.因此,使用该类,我们可以在 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屋!