Skip to content

Instantly share code, notes, and snippets.

@mattorb
Created May 26, 2010 22:31
Show Gist options
  • Save mattorb/415172 to your computer and use it in GitHub Desktop.
Save mattorb/415172 to your computer and use it in GitHub Desktop.
discrete, custom timed (per frame) UIImageView Animation
// keyTimes = array floats for second [(NSNumber)1.2,(NSNumber)2.0] == 2 frames, 1.2 secs for first frame, 2.0 seconds for second frame
- (void) addDiscreteTimedImageAnimation:(NSString *)animationName view:(UIImageView *)imageView images:(NSArray *)images keyTimes:(NSArray *)keyTimes repeatCount:(float)repeatCount onDone:(SEL)callback {
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
NSMutableArray *values = [[NSMutableArray alloc] initWithCapacity:[images count]];
NSMutableArray *keyTimesAsPercent = [[NSMutableArray alloc] initWithCapacity:[keyTimes count]];
double totalDuration = 0.0;
for(UIImage *image in images) {
[values addObject:(id)(image.CGImage)];
}
UIImage *lastImage = [images objectAtIndex:[images count]-1];
[values addObject:(id)(lastImage.CGImage)];
for(NSNumber *frameTime in keyTimes) {
totalDuration+=[frameTime floatValue];
}
float totalSoFar = 0.0;
for(NSNumber *frameTime in keyTimes) {
if (totalSoFar == 0.0) // for discrete timing, the first one is always 0.0
{
[keyTimesAsPercent addObject:[NSNumber numberWithFloat:0.0]];
totalSoFar += [frameTime floatValue];
}
else
{
[keyTimesAsPercent addObject:[NSNumber numberWithFloat:(totalSoFar/totalDuration)]];
totalSoFar += [frameTime floatValue];
}
}
[keyTimesAsPercent addObject:[NSNumber numberWithFloat:1.0]];
animation.values = values;
[values release];
animation.keyTimes = keyTimesAsPercent;
[keyTimesAsPercent release];
animation.delegate = self;
animation.repeatCount = repeatCount;
animation.duration = totalDuration;
animation.fillMode = kCAFillModeForwards;
animation.calculationMode = kCAAnimationDiscrete; // playing
[animation setValue:animationName forKey:@"name"];
[animation setValue:NSStringFromSelector(callback) forKey:@"onDone"];
[[imageView layer] addAnimation:animation forKey:animationName];
}
- (void) animationDidStop:(CAAnimation *)anim finished:(BOOL)finished {
if(finished)
{
ALog(@"Finished animation: %@", [anim valueForKey:@"name"]);
if ([anim valueForKey:@"onDone"] != nil)
{
SEL callback = NSSelectorFromString([anim valueForKey:@"onDone"]);
[self performSelector:callback];
}
}
}
@mattorb
Copy link
Author

mattorb commented May 26, 2010

note .... needed this since the animation support built into UIImageView does not support custom timings per frame, and simple callback feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment