Animating image change – simple way

Let’s imagine we have an UIImageView and we need to change its image in a nice way. Simply changing image would be not enough.
For this particular case we could add one method to UIImageView using Objective-C categories.

-(void)setImage:(UIImage*)image animationDuration:(NSTimeInterval)duration completion:(void (^)(void))completion
    void (^completionBlock)() = [completion copy];
    UIImageView *fadingImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    fadingImageView.alpha = 1.0f;
    fadingImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    fadingImageView.translatesAutoresizingMaskIntoConstraints = YES;
    fadingImageView.contentMode = self.contentMode;
    fadingImageView.image = self.image;
    [self addSubview:fadingImageView];
    self.image = image;

    [UIView animateWithDuration:duration
                         fadingImageView.alpha = 0.0f;
                     completion:^(BOOL finished) {
                         [fadingImageView removeFromSuperview];
                         if (completionBlock)

This method creates a UIImageView with the same size and content mode as our UIImageView. We set its alpha to 1 and its image to current image of our UIImageView. Then we do animation on alpha to hide old image. One more important thing is to remove our temporary UIImageView from hierarchy at the end.

Here is how we should call this method.

[self.imageView setImage:[UIImage imageNamed:@"next-image.jpg"]

We could pass completion block to do some actions when image is fully changed, but it is not necessary.

Of course, category method could be customized even more, specifying animation options, or using other animation techniques. These customizations are up to developer to decide. This example takes use of auto layout and ARC.

You could check out sample project on GitHub for details.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s