一、Value方式
代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
//TODO:Value方式
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.delegate = self;
/**设置移动的路径的点集合**/
NSValue *value1=[NSValue valueWithCGPoint:CGPointMake(100, 100)];
NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(200, 100)];
NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(200, 200)];
NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(100, 200)];
NSValue *value5=[NSValue valueWithCGPoint:CGPointMake(100, 300)];
NSValue *value6=[NSValue valueWithCGPoint:CGPointMake(200, 400)];
animation.values = @[value1,value2,value3,value4,value5,value6];
/**设置重复次数**/
animation.repeatCount = MAXFLOAT;
/**设置是否原路返回**/
animation.autoreverses = YES;
/**设置移动的速度,值越小,速度越快**/
animation.duration = 6.0f;
/**动画完成之后是否移除?**/
animation.removedOnCompletion = NO;
/**动画的填充样式**/
animation.fillMode = kCAFillModeForwards;
/**定义动画的节奏样式**/
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[self.imageView.layer addAnimation:animation forKey:nil];
}
#pragma mark 动画已经结束,可以在这里做一些处理,比如清除图片所占内存
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
}
二、Path方式
//TODO:Path方式
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.delegate = self;
/**创建动画的路线对象,即CGPathRef对象**/
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 150, 200, 250));
CGPathMoveToPoint(path, NULL, 10, 100);
/**路径->直线**/
CGPathAddLineToPoint(path,NULL, 200, 100);
CGPathAddLineToPoint(path,NULL, 200, 200);
CGPathAddLineToPoint(path,NULL, 100, 200);
CGPathAddLineToPoint(path,NULL, 100, 300);
CGPathAddLineToPoint(path,NULL, 200, 400);
/**路径->曲线**/
CGPathAddCurveToPoint(path,NULL,50.0,275.0,150.0,275.0,70.0,120.0);
CGPathAddCurveToPoint(path,NULL,150.0,275.0,250.0,275.0,90.0,120.0);
CGPathAddCurveToPoint(path,NULL,250.0,275.0,350.0,275.0,110.0,120.0);
CGPathAddCurveToPoint(path,NULL,350.0,275.0,450.0,275.0,130.0,120.0);
animation.path = path;
CGPathRelease(path);
animation.autoreverses = YES;
animation.repeatCount = MAXFLOAT;
animation.fillMode = kCAFillModeForwards;
animation.duration = 30.0f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[self.imageView.layer addAnimation:animation forKey:nil];