views:

1852

answers:

2

I need to be able to display an animation over a static image.

Given that MPMoviePlayer gives you no control over anything useful, the only way I can think to do this is to use multiple static images, which we display (one-by-one) to create a "movie like" animation.

I know we could use UIImageView to do this (by setting the UIImageView animationImages property and then calling startAnimation), however we are going to have over 100 images in our animation - so memory usage will be maxed out.

Does anyone have any nice ways to do this kind of animation? Using Core Animation or OpenGL?

My guess is that we'd need to create an image buffer, and as we load new images, we display images from the image buffer??

+3  A: 

You could use a Core Animation CALayer to host your animation, and swap a series of CALayers in and out of that main layer to perform your frame-by-frame animation. You can set the content of an image-frame-hosting CALayer to a CGImageRef using its contents property. A series of CALayers containing your images could be created and stored in an NSMutableArray as needed, then removed when done to minimize memory use.

You can set the transition duration between frames by wrapping the replaceSublayer:with: method call in a CATransaction, like the following:

[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:0.25f] // 1/4th of a second per frame
           forKey:kCATransactionAnimationDuration]; 
[mainLayer replaceSublayer:[imageLayers objectAtIndex:oldImageIndex] with:[imageLayers objectAtIndex:newImageIndex]];
[CATransaction commit];

You might also be able to get away with swapping in and out the CGImageRef in the contents of your main layer, if your frame display time is short enough.

Brad Larson
+1  A: 

Hey folks, I ran into this issue as well. The animationImages approach only works well for 2 to 5 full screen 480x320 images. If you use more images than that it will suck up all the system memory. To address this, I created a class that keeps each image in a PNG file and then renders the PNG file into a UIImage at the right time. That saves a ton of memory because the PNG images are small and it renders fast enough to do 15 FPS on the iPhone hardware.

See example #2 for the source code:

http://www.modejong.com/iPhone/