3.1 Basic Animation
CABasicAnimation
3.2 Keyframe Animations
The code to create the keyframe animation would look like this:
- (CAKeyframeAnimation *)opacityAnimation { CAKeyframeAnimation *animation = [CAKeyframeAnimation animation]; animation.values = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.75], [NSNumber numberWithFloat:0.0], nil]; animation.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.25], [NSNumber numberWithFloat:0.50], [NSNumber numberWithFloat:0.75], nil]; return animation; }
不设置keyTimes时的运行方式:
Keyframes and Paths
- (void)addBounceAnimation { [mover setAnimations:[NSDictionary dictionaryWithObjectsAndKeys: self.originAnimation, @"frameOrigin" , nil]]; } - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { CGFloat xInset = 3.0f * (NSWidth(frame) / 8.0f); CGFloat yInset = 3.0f * (NSHeight(frame) / 8.0f); NSRect moverFrame = NSInsetRect(frame, xInset, yInset); mover = [[NSImageView alloc] initWithFrame:moverFrame]; [mover setImageScaling:NSScaleToFit]; [mover setImage:[NSImage imageNamed:@"photo.jpg" ]]; [self addSubview:mover]; [self addBounceAnimation]; } return self; }
[mover setAnimations:[NSDictionary dictionaryWithObjectsAndKeys: self.originAnimation, @"frameOrigin" , nil]];
frameOrigin:
- (CAKeyframeAnimation *)originAnimation { CAKeyframeAnimation *originAnimation = [CAKeyframeAnimation animation]; originAnimation.path = self.heartPath; originAnimation.duration = 2.0f; originAnimation.calculationMode = kCAAnimationPaced; return originAnimation; }
设置动画运行路径:
originAnimation.path = self.heartPath;
设置动画持续时间:
originAnimation.duration = 2.0f;
设置动画方式:
originAnimation.calculationMode = kCAAnimationPaced;
设置动画路径:
- (CGPathRef)heartPath { NSRect frame = [mover frame]; if(heartPath == NULL) { heartPath = CGPathCreateMutable(); CGPathMoveToPoint(heartPath, NULL, NSMinX(frame), NSMinY(frame)); CGPathAddLineToPoint(heartPath, NULL, NSMinX(frame) - NSWidth(frame),NSMinY(frame) + NSHeight(frame) * 0.85); CGPathAddLineToPoint(heartPath, NULL, NSMinX(frame),NSMinY(frame) - NSHeight(frame) * 1.5); CGPathAddLineToPoint(heartPath, NULL, NSMinX(frame) + NSWidth(frame),NSMinY(frame) + NSHeight(frame) * 0.85); CGPathAddLineToPoint(heartPath, NULL, NSMinX(frame), NSMinY(frame)); CGPathCloseSubpath(heartPath); } return heartPath; }
- (void)bounce { NSRect rect = [mover frame]; [[mover animator] setFrameOrigin:rect.origin]; }
Recall that since we have added an animation to the animations dictionary under the frameOrigin key, the animator will find it during its search and use ours instead of the default animation.