Objc – Simple UIImage fade

Implementation of kCATransitionFade to fade an array of images.

Very easy using CATransition animation:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;[/code]

Full implementation:

I’ve created an UIView class named APFadeImage, and used in Interface Builder.

This the header,

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]@interface APFadeImage ()

@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSArray *images;

@end[/code]

And this the “footer”,

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]@implementation APFadeImage

– (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
self.images = @[[UIImage imageNamed:@"A.jpg"],
[UIImage imageNamed:@"B.jpg"],
[UIImage imageNamed:@"C.jpg"],
[UIImage imageNamed:@"D.jpg"]];

[ NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:@selector(switchImage)
userInfo:nil
repeats:YES];
}
return self;
}

– (void) switchImage
{
CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 2;

[self.imageView.layer addAnimation:transition forKey:nil];

UIImage *currentImage = self.imageView.image;
NSUInteger index = [self.images indexOfObject:currentImage];
index = (index + 1) % [self.images count];

self.imageView.image = self.images[index];
}

@end[/code]

Done.
Add your class in your UIView and go!

Alberto Pasca
Latest posts by Alberto Pasca (see all)