1,给定Path,创建KeyFrame(关键帧)动画
1.1首先创建图层
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor yellowColor].CGColor;
layer.position = CGPointMake(100, 100);
layer.bounds = CGRectMake(0, 0, 100, 100);
[self.view.layer addSublayer:layer];
self.layer = layer;
1.2创建KeyFrame动画,并添加到图层上
// 按照椭圆的路径做动画
- (void)testKeyFrameAnimation
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.delegate = self;
animation.keyPath = @"position";
animation.duration = 2;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 150));
animation.path = path;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:animation forKey:nil];
}
1.3通过touch方法调用,KeyFrame方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self testKeyFrameAnimation];
}
2.给定values数组,创建KeyFrame动画
2.1创建KeyFrame动画,并添加到图层上
- (void)testKeyFrameAnimation2
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.delegate = self;
animation.keyPath = @"position";
animation.duration = 2;
NSValue *v1 = [NSValue valueWithCGPoint:CGPointMake(50, 100)];
NSValue *v2 = [NSValue valueWithCGPoint:CGPointMake(50, 200)];
NSValue *v3 = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
NSValue *v4 = [NSValue valueWithCGPoint:CGPointMake(200, 100)];
NSValue *v5 = [NSValue valueWithCGPoint:CGPointMake(50, 100)];
animation.values = @[v1,v2,v3,v4,v5];
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:animation forKey:nil];
}
2.2修改touch方法,使得touch时,调用testKeyFrameAnimation2
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self testKeyFrameAnimation2];
}
- (void)animationDidStart:(CAAnimation *)anim
{
NSLog(@"开始动画");
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
NSLog(@"结束动画 %d",flag);
}