Search code examples
iosiphoneanimationuiimageviewuiimage

How to animate the change of image in an UIImageView?


I have an UIImageView with an image. Now I have a completely new image (graphic file), and want to display that in this UIImageView. If I just set

myImageView.image = newImage;

the new image is visible immediately. Not animatable.

I want it to nicely fade into the new image. I thought maybe there's a better solution than just creating a new UIImageView on top of that and blending with animation?


Solution

  • I am not sure if you can animate UIViews with fade effect as it seems all supported view transitions are defined in UIViewAnimationTransition enumeration. Fading effect can be achieved using CoreAnimation. Sample example for this approach:

    #import <QuartzCore/QuartzCore.h>
    ...
    imageView.image = [UIImage imageNamed:(i % 2) ? @"3.jpg" : @"4.jpg"];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    
    [imageView.layer addAnimation:transition forKey:nil];