Animated Gif – Animated Images – iPhone Style

July 16, 2009

Ah, the animated gif, a throwback to the early days of web development and simple animation. In this post I’ll show you how to use a UIImageView to create a similar effect that you get with an animated gif.

Below I’ve inserted the animated gif that I’ll use as a template for the iPhone app we’ll write in this post.


Animated gifs are nothing more than a series of images, encapsulated within one gif file, that are displayed in sequence. Within an animated gif one can specify the duration that each image (aka frame) is displayed, which offers a wide range effects that you can achieve.

Animated Images on the iPhone
To achieve a similar effect in an iPhone app, we create a UIImageView and set the animationImages property to point to an array of images. Not unlike the animated gif, we now have a series of images in which we can control the amount of time to complete one cycle of the images, as well as the repeat count of how many times to cycle through the animation.

To keep the example short, I’ll use only one class, the application delegate. Here is how I’ve defined the delegate class:

@interface animationAppDelegate : NSObject <UIApplicationDelegate>
{
  UIImageView   *animatedImages;
  NSMutableArray *imageArray;
  UIWindow *window;
}

Not much here, the UIImageView, an array to hold the images and the UIWindow for the output.

The code for the implementation of the app delegate follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#import "animationAppDelegate.h"
 
#define IMAGE_COUNT       36
#define IMAGE_WIDTH       240
#define IMAGE_HEIGHT      180
#define STATUS_BAR_HEIGHT 20
#define SCREEN_HEIGHT     460
#define SCREEN_WIDTH      320
 
@implementation animationAppDelegate
 
@synthesize window;
 
- (void)stopAnimation
{
  [animatedImages stopAnimating];
}
 
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
  window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 
  // Array to hold jpg images
  imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];
 
  // Build array of images, cycling through image names
  for (int i = 0; i < IMAGE_COUNT; i++)
    [imageArray addObject:[UIImage imageNamed:
              [NSString stringWithFormat:@"Frame_%d.jpg", i]]];
 
  // Animated images - centered on screen
   animatedImages = [[UIImageView alloc] 
     initWithFrame:CGRectMake(
        (SCREEN_WIDTH / 2) - (IMAGE_WIDTH / 2), 
        (SCREEN_HEIGHT / 2) - (IMAGE_HEIGHT / 2) + STATUS_BAR_HEIGHT,
        IMAGE_WIDTH, IMAGE_HEIGHT)];
  animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
 
  // One cycle through all the images takes 1 seconds
  animatedImages.animationDuration = 1.0;
 
  // Repeat forever
  animatedImages.animationRepeatCount = 0;
 
  // Add subview and make window visible
  [window addSubview:animatedImages];
  [window makeKeyAndVisible];
 
  // Start it up
  animatedImages.startAnimating;
 
  // Wait 5 seconds, then stop animation
  [self performSelector:@selector(stopAnimation) withObject:nil afterDelay:5];
 
}
 
- (void)dealloc 
{
  [imageArray release];
  [animatedImages release];
  [window release];
  [super dealloc];
}
 
@end

How it Works
On lines 3 – 5 we define the attributes for the images in the animation. There are a total of 36 images, each is 240 x 180 pixels. On line 22 the array is defined which will hold the images and lines 25 – 27 the images are added to the array. You can decipher from the code that the images I am using have file names in the format: Frame_1.jpg, Frame_2.jpg, Frame_3.jpg, etc.

On lines 30 – 34 we allocate an UIImageView object and configure the frame so the image is centered on the device display. Line 35 sets the animationImages property to the array of images created above.

Line 38 sets the duration for one cycle through all the images. We specify the images are to cycle indefinitely by setting the animationRepeatCount to -1 on line 41.

At this point we are pretty much good to go, all we need to do is add the UIImageView object as a subview (line 44) and start the animation (line 48).

Application in the iPhone Simulator
The movie below shows how the application looks when running in the iPhone simulator:

Porting Animated Gif to iPhone
Not unlike I did for the example above, if you have an animated gif that you would like to use within an iPhone app, it’s as simple as extracting/saving each image inside a gif and using a sequential naming convention. I opened the original gif file and manually saved each frame in the image to a jpg file. There are a number of tools that will do the extraction/saving/renaming for you (search for gif extractor).

With all the images saved as separate file, swap the image attributes in the #define section and update the code on line 27 to match the filename you used for saving each file.

Xcode Project Source Code
Download the Animation Xcode project.

  Animated gif of Newtons cradle, courtesy: Wikipedia  


26 comments

Hi There,
Do you know of a way to use some sort of notification event when it stopped if you had the animation run only once or twice?
Thanks,
Adrian

by Adrian S on Aug 16, 2009. Reply #

Hi Adrian,

You could set up your own notification or timer based on the animation duration, however, that would probably lack the accuracy you are looking for.

John

by John Muchow on Aug 16, 2009. Reply #

Hi, do you know why app is crashed if i use more then 150 images to animate 6 sec, since i want to use 25f/s ?

by Vitaly on Oct 26, 2009. Reply #

You may be running out of memory. Try cutting back the images and see if that solves the problem.

by John Muchow on Oct 26, 2009. Reply #

Hi, do you know is there any method to make the UIImageView built animation to be able to send it thru email? Means sending the animation being built in the apps thru email or even MMS. Or is there any way to make the animation in the apps and eventually send by email/MMS.Thanks.

by BC on Dec 30, 2009. Reply #

BC, the only way that I can think of to send by email would be if you write the code to convert a series of images into an animated gif, save that as a file (on device) and then email that file as an attachment. There is no built in means with the iPhone SDK for this capability.

by John Muchow on Jan 1, 2010. Reply #

This is just what I was looking for.

For some reason, It builds and runs fine, yet I only get a black screen on the iphone and simulator. I’ve looked at all the image file names I’m using and made the changes in code to reflect my naming structure. and I’m wondering if the center-on-screen code is what the problem is.

My image is 480×320 (and I scaled it down to 460×320 to allow for status bar) but I only get a black screen.

Any Idea what I’m doing wrong?

Thank you.

Mikey

by Mikey on May 5, 2010. Reply #

Mikey, you may want to run a test to make sure your images can be displayed. For example, set one of the images as the background on a view to make sure it can be displayed.

by John Muchow on May 6, 2010. Reply #

I need to load 150 images, and I have found out
that memory wise this is not possible using this method.
Is there any way I can make a video or animation to be
played on the background of my application?

by kalel on Jun 5, 2010. Reply #

Hi…awesome article…thanks. Please tell me what software did you use to create and render the 3D picture? It’s really cool. Assuming that you build it yourself, did you have to build wireframe models for all those objects (balls, tablet, and wire hanger?). Thanks again for a great article.

by Larry Brown on Aug 3, 2010. Reply #

Larry,

I can’t take credit for the 3D artwork, I found the image here: Graphics Interchange Format

by John Muchow on Aug 3, 2010. Reply #

Awesome, It is a good solution that I am looking for. No large video file for my project

Thank you,
Gift

by Gift on Aug 9, 2010. Reply #

Thank you.
Very useful article.

by asdf on Apr 22, 2011. Reply #

i want to move the single object . from one position to another position.

can u help me .

Thanks

Arunjack

by Arunjack on Jun 21, 2011. Reply #

You can change the frame (x and y coordinates) to change the image location.

by John Muchow on Jun 21, 2011. Reply #

Excellent and articulate tutorial. Thank you. You saved my day!

by premal on Aug 10, 2011. Reply #

Hello John,

First of all, thank you a lot for this post, it helped me a lot.

I would like to ask you something: i want to show this animation when you touch the screen and it’s working fine but, once it stops, it doesn’t works no more. I think it’s due to something i’m doing wrong with “animatedImages” or “imageArray” but i have no idea. Could you help me, please?

Thanks in advance.

by Jorge on Sep 16, 2011. Reply #

Ok, i’ve found the solution by myself. I’ve added next two line in the method “stopAnimation”:

[window addSubview:self.view];
[window makeKeyAndVisible];

I hope it helps anyone!

by Jorge on Sep 17, 2011. Reply #

Thanks for posting this. I’ve been trying to figure out how to loop through image files rather than listing each one. Nice tutorial. Keep up the good work :)

by gg on Sep 28, 2011. Reply #

Great help!

by Maria on Dec 16, 2011. Reply #

This is nice, but it is not completely like an animated gif. Animated gif’s allow for a separate duration between frames. Is there a way to have a series of frames with different durations between them? Now that is an example that is well needed. Seems like no one has posted an example of how to accomplish that.

by Tony on Jan 12, 2012. Reply #

I display the animated gif with a html page. I want the user to fly(move) the animated helicopter around the iphone screen. Any ideas? Excellent post…thanks…bob

by bob on Jul 25, 2012. Reply #

That would require much more in depth code, you may want to look into core animation.

by John Muchow on Jul 25, 2012. Reply #

I have a series of images I’m animating and it plays in the intro of my app. There is some network traffic going on in the background, but oftentimes, when I first launch the app, the animation doesn’t play smoothly, and it appears that some of the frames are skipped over, so it looks like it jumps to the end of the animation. Do you have any suggested solutions I should try so that I can ensure a smooth animation every time?

by Brian Roberson on Jan 7, 2013. Reply #

You may want to look into one of the native graphics frameworks such as core animation, that may provide a better UI experience.

by John Muchow on Jan 7, 2013. Reply #

Thanks John. I’ll look into it and get back to you.

by Brian Roberson on Jan 8, 2013. Reply #

Leave a Comment