Steffan Davies
Steffan Davies

Reputation: 159

Trouble with animation on UIImageView

I have 7 images which i'm trying to make fade in/out of 1 ImageView. I have stored all the images in an array, and then have a loop to display each image and fade into the next, however, when i run the program only the last 2 images show up. Any ideas on why this is? and how to fix it? Code is below.

imageArray = [NSArray arrayWithObjects:
              [UIImage imageNamed:@"image 0.jpg"],
              [UIImage imageNamed:@"image 1.jpg"],
              [UIImage imageNamed:@"image 2.jpg"],
              [UIImage imageNamed:@"image 3.jpg"],
              [UIImage imageNamed:@"image 4.jpg"],
              [UIImage imageNamed:@"image 5.jpg"],
              [UIImage imageNamed:@"image 6.jpg"],
              nil];
            self.imageview.backgroundColor = [UIColor blackColor];
              self.imageview.clipsToBounds = YES;

int count = [imageArray count];
for (int i = 0; i <count-1 ; i++)
{
    UIImage *currentImage = [imageArray objectAtIndex: i];
    UIImage *nextImage = [imageArray objectAtIndex: i +1];
    self.imageview.image = [imageArray objectAtIndex: i];
    [self.view addSubview:self.imageview];
    CABasicAnimation *crossFade = [CABasicAnimation animationWithKeyPath:@"contents"];
    crossFade.duration = 5.0;
    crossFade.fromValue = (__bridge id)(currentImage.CGImage);
    crossFade.toValue = (__bridge id)(nextImage.CGImage);
    [self.imageview.layer addAnimation:crossFade forKey:@"animateContents"];
    self.imageview.image = nextImage;

};

Upvotes: 0

Views: 193

Answers (1)

Ismael
Ismael

Reputation: 3937

Some things to note:

1) You are doing everything synchronously on a loop that has no delay between each transition, there's no point in animating a if on the next loop it will be replaced by the next and so on, until the last 2. Also, you are adding your imageView as a subview every time, also unnecessary.

2) You are changing the .image property of the imageView, and then changing the contents of the layer. Might as well use an UIView and have the same effect.

My recommendation is to make a method to swap from one image to the next, and have a NSTimer call the function every x amount of seconds until you passed through them all.

Edit: For the future:

self.imageview.backgroundColor = [UIColor blackColor];
self.imageview.clipsToBounds = YES;

are completely unnecessary :)

The .backgroundColor is drawn over by the UIImage you are displaying.

The .clipsToBounds is the default behavior of UIImageView (it shrinks/expands your image to it's size, but never draws outside)

Upvotes: 1

Related Questions