Here is a real easy way to do simple animation in Cocoa-Touch.
When you are doing iPhone programming you have a few ways to do graphics and simple animation. If you are doing extensive custom graphics you must use Core Graphics and Core Animation.
However, if you simply want to animate a simple series of images similar to an animated gif you can simple use UIImageView. What you need to do is load your series of images into the image view and then send a message to your image view to start animating. It is very simple.
Here is how you would do this in code.
//Set up image view
UIImage *image = [UIImage imageNamed:@"button001.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"button001.png"],
[UIImage imageNamed:@"button002.png"],
[UIImage imageNamed:@"button003.png"],
[UIImage imageNamed:@"button004.png"],
[UIImage imageNamed:@"button005.png"],
nil];
[imageView startAnimating];
[self.view addSubview:imageView];
What the above code will do is flash through each image in the array. It will transition smoothly so if you wanted to you could feel it a series of images like a cartoon strip or a flickering flame and it will appear to move like a film.
Wait – Memory Leak!
Ok, so as was just noted by @alexcschaefer (on Twitter) if you follow the above example you will get a memory leak. I had put everything in essentially one method for clarity. But, generally you will do something like this in the context of a view controller. You would probably declare the imageView to stay in scope throughout the view controller’s lifetime and release it in your dealloc method like so:
#import "Animation.h"
@implementation Animation
UIImageView *imageView;
- (void)viewDidLoad {
[super viewDidLoad];
//Set up image view
UIImage *image = [UIImage imageNamed:@"button001.png"];
imageView = [[UIImageView alloc] initWithImage:image];
imageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"button001.png"],
[UIImage imageNamed:@"button002.png"],
[UIImage imageNamed:@"button003.png"],
[UIImage imageNamed:@"button004.png"],
[UIImage imageNamed:@"button005.png"],
nil];
[imageView startAnimating];
[self.view addSubview:imageView];
}
- (void)dealloc {
[imageView release];
[super dealloc];
}
@end
Or you could simply declare it in viewDidLoad and then release after adding it the the subview collection. As always, use your best judgement.




How to do Animation With Cocoa Touch…
You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…