iOS 11个动画gif在UIImageView中显示
iOS 11 animated gif display in UIImageView
我以为 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
}
这应该如何运作?
iOS 11 确实带来了对动画 gif 的原生理解,但令人愤怒的是,这种理解并未内置到 UIImageView 中。 你 仍需将动画 gif 转换为一系列 UIImage。苹果现在提供示例代码,在ImageIO框架方面:
该代码实现了一个 AnimatedImage class,它本质上是从原始动画 gif 中提取的 CGImage 的集合。因此,使用 class,我们可以在 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:[=10=])}
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()
}
不幸的是,GIF 的帧间时间在帧之间可能会有所不同,因此使用 ImageIO 加载帧然后将它们设置为 UIImageView 上的动画图像的答案需要正确提取时间并将它们考虑在内.
我推荐 Flipboard 的 FLAnimatedImage,它可以正确处理 GIF。
https://github.com/Flipboard/FLAnimatedImage.
我以为 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
}
这应该如何运作?
iOS 11 确实带来了对动画 gif 的原生理解,但令人愤怒的是,这种理解并未内置到 UIImageView 中。 你 仍需将动画 gif 转换为一系列 UIImage。苹果现在提供示例代码,在ImageIO框架方面:
该代码实现了一个 AnimatedImage class,它本质上是从原始动画 gif 中提取的 CGImage 的集合。因此,使用 class,我们可以在 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:[=10=])}
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()
}
不幸的是,GIF 的帧间时间在帧之间可能会有所不同,因此使用 ImageIO 加载帧然后将它们设置为 UIImageView 上的动画图像的答案需要正确提取时间并将它们考虑在内.
我推荐 Flipboard 的 FLAnimatedImage,它可以正确处理 GIF。 https://github.com/Flipboard/FLAnimatedImage.