top of page

IOS Programming Part2: Creating animation with UIImageView

Step1: Drag imageView from object library and drop it on your user interface like below image. Also add two buttons on the interface, both of them will be used to control the animation.

Step2: create outlet variable for your imageview and set Action for your buttons that you created in the step1.

Step3: add the following code inside viewdidload method

NSMutableArray *imgNames = [[NSMutableArray alloc] init];

[imgNames addObject:@"cartoon1"];

[imgNames addObject:@"cartoon2"];

[imgNames addObject:@"cartoon3"];

[imgNames addObject:@"cartoon4"];

[imgNames addObject:@"cartoon5"];

m_ImageList = [[NSMutableArray alloc] init];

for(NSInteger i=0; i<[imgNames count]; i++){

NSString *imgName = [imgNames objectAtIndex:i];

NSString *thePath = [[NSBundle mainBundle] pathForResource:imgName ofType:@"png"];

UIImage *img = [[UIImage alloc] initWithContentsOfFile:thePath];

[m_ImageList addObject:img];

}

_imgView.animationImages = m_ImageList;

_imgView.animationDuration = 0.5f;

_imgView.image = [m_ImageList objectAtIndex:0];

Let see how the code work, First we create array object which is used to keep all imageName that we want to use it as part of animation. Then we use method initwithcontentsotfile to load image from file and kept the image to UIimage object. After that, The created UIImage object is added to the m_ImageList. Now, it is time to link it to ImageView to get the animation work. There are two properties that need to be set, "animationImages", "animationDuration" is the duration of changing between one image to another image in the imageList, At last, we set default image for this UIImageView object as the first image in the imageList.

Step4: Now, Time to start animation when user touch on the button, To do this, Let's add some code to make it work. Your code for two buttons should look like this

- (IBAction)PlayBtn:(id)sender {

[_imgView startAnimating];

}

- (IBAction)StopBtn:(id)sender {

[_imgView stopAnimating];

}

The animation will be played by using method startAnimating. it will be called when user touched on the play button. The animation will be stopped when user touch on stop button.


bottom of page