iPhone Animation: Fade Between Multiple Images

Maybe you want to have a background of images that slowly fade from one image to the next. Or maybe you want to do a photo slideshow with a nice dissolve between the two pictures. We tried a few different approaches before we found the right way to get this to work for us. Here’s a little bit of sample code to show you how to do it.

We need three instance variables: two image views to draw into, and a queue for all the images.

@interface MyViewController : UIViewController {
	IBOutlet UIImageView *backgroundA;
	IBOutlet UIImageView *backgroundB;
	NSMutableArray *backgroundImageQueue;
}

In the implementation we need to modify viewDidLoad to setup our objects. We initialize a queue with a series of images. The order is backwards, so the last image in the queue will be displayed first.

We then create a nextAnimation method, which uses Core Animation to fade between the two images. When the animation is done, it calls itself.


@implementation MyViewController
	
- (void)viewDidLoad {
	[super viewDidLoad];
	backgroundImageQueue = [[NSMutableArray alloc] init];
	[backgroundImageQueue addObject:
[UIImage imageNamed:@"waterfall.jpg"]]; [backgroundImageQueue addObject:
[UIImage imageNamed:@"clouds.jpg"]]; /* Add any more images to the queue */ backgroundB.image = [backgroundImageQueue
objectAtIndex:[backgroundImageQueue count] - 1]; [backgroundImageQueue insertObject:
backgroundB.image atIndex:0]; [backgroundImageQueue removeLastObject]; backgroundA.alpha = 1.0; backgroundB.alpha = 0.0; [self nextAnimation]; } -(void)nextAnimation { backgroundA.image = backgroundB.image; backgroundB.image = [backgroundImageQueue
objectAtIndex:[backgroundImageQueue count] - 1]; [backgroundImageQueue insertObject:
backgroundB.image atIndex:0]; [backgroundImageQueue removeLastObject]; backgroundA.alpha = 1.0; backgroundB.alpha = 0.0; [UIView beginAnimations:@"fade" context:NULL]; [UIView setAnimationDuration:6]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:
@selector(nextAnimation)]; backgroundA.alpha = 0.0; backgroundB.alpha = 1.0; [UIView commitAnimations]; } @end

I hope this helps you save a little bit of time.

-Dustin