the codemonky

ramblings, musing and code snippets from shawn veader
Jun 24
Permalink

Animated GIFs and UIImageViews

OK, so while building an iPhone app last night I ran into a little snag. We are using an animated GIF on the loading screen to allow the user to see something pretty while they wait.

Being naive, I assumed the UIImageView would display the animated GIF. Well… I was partially right. It does display the GIF but only the first frame.

Then the Google hunt began…

After some searching, I had found that you can set the animatedImages property of a UIImageView to a NSArray that contains each frame of the animated GIF and then call the startAnimating method to “play” it.

OK, great…. now how do I get the frames out? After more Googling I just tried Preview.app on a wild hair. I’m glad to report that it shows the animated GIF but in the drawer of the app, it also has each frame. Simply drag each of these out and boom! you’re set.

Now for the code sample.

UIImage *frame0 = [UIImage imageNamed:@"frame0.png"];
// ... more frames here ...
UIImage *frameN = [UIImage imageNamed:@"frameN.png"];

// animatedGif is a UIImageView initialized in your NIB or elsewhere.
animatedGif.animatedImages = [[NSArray alloc] initWithObjects:frame0
                                                              ....
                                                              frameN,
                                                              nil];
[animatedGif startAnimating];

There are a few other things you can play with like the animatedDuration and animatedRepeatCount properties. But you can figure those out.

And a link to the UIImageView documentation for completeness… UIImageView