IOS 11 animated gif display in UIImageView

I thought iOS 11 was finally supposed to bring support for animated gifs? But I tried this and I did not see the 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 } 

How should this work?

+11
ios animation uiimageview ios11 animated-gif
source share
2 answers

iOS 11 does provide a natural understanding of animated gifs, but this understanding, for no reason, is not built into UIImageView. You don't care to translate an animated gif into a UIImages sequence. Apple now provides sample code in terms of the ImageIO structure:

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

This code implements the AnimatedImage class, which is essentially a collection of CGImages extracted from the original animated gif. Thus, using this class, we can display and animate an 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() } 
+15
source share

Unfortunately, GIF inter-frame synchronization can vary between frames, so the answers that use ImageIO to load frames and then set them as animated images in UIImageView need to correctly extract the timings and take them into account.

I recommend Flipboard FLAnimatedImage, which handles GIFs correctly. https://github.com/Flipboard/FLAnimatedImage .

+1
source share

All Articles