Murali Patteboyina Murali Patteboyina - 2 years ago 103
iOS Question

iOS Crossfading Multiple Images in imageviews

I have 9 images that I need to cross fade. I tried to do animation with animationImages method of imageview. But unfortunately, it does not support cross fading effect between images. Can anybody tell me how to achieve this?

Answer Source

I usually use Core Animation, specifically CABasicAnimation,

I used this recently, an image view with a couple of gesture recognizers for left and right swipe. Check out the fading animations I am using:

_someImageView = [[UIImageView alloc] initWithFrame:myFrame];
_someImageView.image = [myArrayOfImages objectAtIndex:0];
[self.view addSubview:_someImageView];
[_someImageView release];

_currentImageIndex = 0;

_someImageView.userInteractionEnabled = YES;

UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage:)];
swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[_someImageView addGestureRecognizer:swipeLeftGesture];
[swipeLeftGesture release];

UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage:)];
swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
[_someImageView addGestureRecognizer:swipeRightGesture];
[swipeRightGesture release];

Then this is called every time I swipe, or if you prefer to do something time based, then have your timer call this, just make sure you increment a counter so that you can loop the images:

- (void)changeImage:(UISwipeGestureRecognizer *)swipe{

    NSArray *images = [myArrayOfImages images];
    NSInteger nextImageInteger = _currentImageIndex;

    if(swipe.direction == UISwipeGestureRecognizerDirectionLeft)

    if(nextImageInteger < 0)
        nextImageInteger = images.count -1;
    else if(nextImageInteger > images.count - 1)
        nextImageInteger = 0;

    _currentImageIndex = nextImageInteger;

    UIImage *target = [images objectAtIndex:_currentImageIndex];

    CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:@"contents"];
    crossFade.duration      = 0.5;
    crossFade.fromValue     = _someImageView.image;
    crossFade.toValue       = target;
    [_someImageView.layer addAnimation:crossFade forKey:@"animateContents"];
    _someImageView.image = target;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download