Home / iPhone Tips and Tutorials

Animating a Series of Images "In Place"

Although I explain animation using the UIView methods earlier in this article, this section shows you a way to animate a series of images "in place." To make the TestDrive button blink, forexample, add the bolded code in Listing-15 to RTViewController.m. As you can see in the listing, only a single line of code is needed to animate the button.

Listing 10-15: Creating a Blinking Button

- (void)viewDidLoad
{
  [super viewDidLoad];
  self.title = @"Road Trip";

  NSURL* backgroundURL = [NSURL fileURLWithPath:[[NSBundle
	mainBundle]pathForResource:@"CarRunning"
	ofType:@"aif"]];
  backgroundAudioPlayer = [[AVAudioPlayer alloc]
	initWithContentsOfURL:backgroundURL error:nil];
  backgroundAudioPlayer.numberOfLoops = -1;
  [backgroundAudioPlayer prepareToPlay];

  NSURL* burnRubberURL = [NSURL fileURLWithPath:[[NSBundle
	mainBundle] pathForResource:@"BurnRubber"
	ofType:@"aif"]];
  AudioServicesCreateSystemSoundID((__bridge CFURLRef)
	burnRubberURL, &burnRubberSoundID);
  [testDriveButton setBackgroundImage:[UIImage
	animatedImageNamed:@"Button" duration:1.0 ]
	forState:UIControlStateNormal];
}

You could have also programmatically added the background image by sending the button the setBackgroundImage:forState: message. Normally, you might think of making the background image a single image. However, animatedImageNamed:duration: and some similar methods use a series of files, each displayed for a duration you specify, instead. This type of method enables you to animate (this time in place) not only a button but any image by simply supplying a series of images:

[testDriveButton setBackgroundImage:
  [UIImage animatedImageNamed:@"Button" duration:1.0]
			forState:UIControlStateNormal];

In the animatedImageNamed: method, you supply a base name of an image to animate. The method will append a zero to the base name and load that image (in this case, Button0). After the time that you specify in duration has elapsed, the animatedImageNamed: method appends the next number (in this case, 1) to the base image name and attempts to load it and the remainder of images (up to 1,024 images) until it runs out of images, and then it starts over.

In the Project navigator, open the disclosure triangle for the RoadTrip Resources group. If you look in the RoadTrip Resources group, you see two images, Button0 and Button1 - with Button being the base name you specified. This is an "in place" animation, so all images included in the animated image should share the same size and scale.

If you select each image in the Project navigator, you can see that they are slightly different colors, and each will display for 1.0 seconds (duration: 1.0). This makes the button blink and certainly adds some life to the Main view.

[Previous] [Contents]