Add Gif Animated Image to Iphone UIImageView

I need to load an animated Gif image from a URL in a UIImageview.

When I used regular code, the image did not load.

Is there any other way to download animated gif images?

+73
objective-c iphone uiimageview
Dec 08 '10 at
source share
12 answers
UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; animatedImageView.animationImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"image1.gif"], [UIImage imageNamed:@"image2.gif"], [UIImage imageNamed:@"image3.gif"], [UIImage imageNamed:@"image4.gif"], nil]; animatedImageView.animationDuration = 1.0f; animatedImageView.animationRepeatCount = 0; [animatedImageView startAnimating]; [self.view addSubview: animatedImageView]; 

You can upload more than one gif image.

You can share your gif using the following ImageMagick command:

 convert +adjoin loading.gif out%d.gif 
+133
Dec 08 '10 at
source share

This found an acceptable answer, but I recently met the UIImage UIImage + animatedGIF extension. It provides the following category:

 +[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url] 

allows you to simply:

 #import "UIImage+animatedGIF.h" UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]]; 

It works like magic.

+50
Mar 12 '13 at 9:01
source share

Here is the best solution to use Gif Image. Add SDWebImage from Github to your project.

 #import "UIImage+GIF.h" _imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"]; 
+22
May 7, '15 at 10:39
source share

Mark this link

https://github.com/mayoff/uiimage-from-animated-gif/blob/master/uiimage-from-animated-gif/UIImage%2BanimatedGIF.h

and import these classics UIImage + animatedGIF.h, UIImage + animatedGIF.m

Use this code

  NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"]; NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"]; NSURL *url=[[NSURL alloc] initFileURLWithPath:path]; imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url]; 

Hope this is helpful

+12
Aug 14 '13 at 10:20
source share

If you do not want to use a third-party library,

 extension UIImageView { func setGIFImage(name: String, repeatCount: Int = 0 ) { DispatchQueue.global().async { if let gif = UIImage.makeGIFFromCollection(name: name, repeatCount: repeatCount) { DispatchQueue.main.async { self.setImage(withGIF: gif) self.startAnimating() } } } } private func setImage(withGIF gif: GIF) { animationImages = gif.images animationDuration = gif.durationInSec animationRepeatCount = gif.repeatCount } } extension UIImage { class func makeGIFFromCollection(name: String, repeatCount: Int = 0) -> GIF? { guard let path = Bundle.main.path(forResource: name, ofType: "gif") else { print("Cannot find a path from the file \"\(name)\"") return nil } let url = URL(fileURLWithPath: path) let data = try? Data(contentsOf: url) guard let d = data else { print("Cannot turn image named \"\(name)\" into data") return nil } return makeGIFFromData(data: d, repeatCount: repeatCount) } class func makeGIFFromData(data: Data, repeatCount: Int = 0) -> GIF? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { print("Source for the image does not exist") return nil } let count = CGImageSourceGetCount(source) var images = [UIImage]() var duration = 0.0 for i in 0..<count { if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) { let image = UIImage(cgImage: cgImage) images.append(image) let delaySeconds = UIImage.delayForImageAtIndex(Int(i), source: source) duration += delaySeconds } } return GIF(images: images, durationInSec: duration, repeatCount: repeatCount) } class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double { var delay = 0.0 // Get dictionaries let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0) if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false { return delay } let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self) // Get delay time var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if delayObject.doubleValue == 0 { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } delay = delayObject as? Double ?? 0 return delay } } class GIF: NSObject { let images: [UIImage] let durationInSec: TimeInterval let repeatCount: Int init(images: [UIImage], durationInSec: TimeInterval, repeatCount: Int = 0) { self.images = images self.durationInSec = durationInSec self.repeatCount = repeatCount } } 

Use,

 override func viewDidLoad() { super.viewDidLoad() imageView.setGIFImage(name: "gif_file_name") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) imageView.stopAnimating() } 

Make sure you add the gif file to the project, and not to the .xcassets folder.

+6
May 24 '18 at 20:07
source share

This does not meet the requirements of using UIImageView, but perhaps it will simplify you. Do you consider using UIWebView?

 NSString *gifUrl = @"http://gifs.com"; NSURL *url = [NSURL URLWithString: gifUrl]; [webView loadRequest: [NSURLRequest requestWithURL:url] 

If you want, instead of linking to a URL that requires the Internet, you can import the HTML file into your Xcode project and set the root to a string.

+5
May 21 '13 at 20:56
source share

Here is an interesting library: https://github.com/Flipboard/FLAnimatedImage

I tested a demo and it works great. This is a child of UIImageView. So I think you can use it in your storyboard too.

Greetings

+3
Apr 09 '15 at 13:37
source share

I know that the answer is already approved, but it’s hard not to try to share the fact that I created a built-in infrastructure that adds Gif support for iOS, which also feels like if you use any other UIKit Framework class.

Here is an example:

 UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData]; anUiImageView.image = gif; 

Download the latest version https://github.com/ObjSal/UIGifImage/releases

- Sal

+3
Aug 15 '15 at 23:21
source share

If you need to load the gif image from the URL, you can always insert the gif into the image tag in the UIWebView .

+2
Mar 11 '13 at 6:08
source share

SWIFT 3

Here is an update for those who need the Swift version!

A few days ago I needed to do something like this. I download some data from the server according to certain parameters, and in the meantime I wanted to show another gif image "download". I was looking for an option to do this using UIImageView , but unfortunately I could not find something for this without breaking the .gif image. So I decided to implement the solution using UIWebView , and I want to share it:

 extension UIView{ func animateWithGIF(name: String){ let htmlString: String = "<!DOCTYPE html><html><head><title></title></head>" + "<body style=\"background-color: transparent;\">" + "<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" + "</body>" + "</html>" let path: NSString = Bundle.main.bundlePath as NSString let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) let gifView = UIWebView(frame: frame) gifView.isOpaque = false // The drawing system composites the view normally with other content. gifView.backgroundColor = UIColor.clear gifView.loadHTMLString(htmlString, baseURL: baseURL) var s: [UIView] = self.subviews for i in 0 ..< s.count { if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() } } self.addSubview(gifView) } func animateWithGIF(url: String){ self.animateWithGIF(name: url) } } 

I made an extension for UIView that adds a UIWebView as a subview and displays .gif images by simply passing its name.

Now in my UIViewController I have a UIView called "loadView", which is my loading indicator and whenever I wanted to show a .gif image, I did something like this:

 class ViewController: UIViewController { @IBOutlet var loadingView: UIView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureLoadingView(name: "loading.gif") } override func viewDidLoad() { super.viewDidLoad() // .... some code // show "loading" image showLoadingView() } func showLoadingView(){ loadingView.isHidden = false } func hideLoadingView(){ loadingView.isHidden = true } func configureLoadingView(name: String){ loadingView.animateWithGIF(name: "name")// change the image } } 

when I wanted to change the gif image, I just called the configureLoadingView() function the name of my new .gif image and by calling showLoadingView() , hideLoadingView() everything worked fine fine!

BUT...

... if you split the image, you can animate it on one line using the static UIImage method called UIImage.animatedImageNamed as follows:

imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)

From the docs:

This method loads a series of files by adding a series of numbers to the base file name specified in the name parameter. All images included in the animated image must be the same size and scale.

Or you can do this using the UIImage.animatedImageWithImages method as follows:

 let images: [UIImage] = [UIImage(named: "imageName1")!, UIImage(named: "imageName2")!, ..., UIImage(named: "imageNameN")!] imageView.image = UIImage.animatedImage(with: images, duration: 1.0) 

From the docs:

Creates and returns an animated image from an existing set of images. All images included in the animated image must be the same size and scale.

+1
Jun 19 '15 at 20:06
source share

You can use https://github.com/Flipboard/FLAnimatedImage

 #import "FLAnimatedImage.h" NSData *dt=[NSData dataWithContentsOfFile:path]; imageView1 = [[FLAnimatedImageView alloc] init]; FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:dt]; imageView1.animatedImage = image1; imageView1.frame = CGRectMake(0, 5, 168, 80); [self.view addSubview:imageView1]; 
0
Aug 23 '16 at 12:20
source share

Swift 3:

As suggested above, I am using FLAnimatedImage with FLAnimatedImageView. And I load the gif as a dataset from xcassets. This allows me to provide various gifs for iphone and ipad for the look and use of applications. This is a lot more than I tried. It is also easy to pause using .stopAnimating ().

 if let asset = NSDataAsset(name: "animation") { let gifData = asset.data let gif = FLAnimatedImage(animatedGIFData: gifData) imageView.animatedImage = gif } 
0
Feb 02 '17 at 18:11
source share



All Articles