CABasicAnimation(基础动画)只能冲一个属性的数值(formValue)变为属性的另一个数值(toValue),而 关键帧动画(CAKeyframeAnimation)是使用一个NSArray来保存这些数值。
属性说明:
1.values:里面的元素成为(关键帧)。动画会在在指定的时间(duration)内,根据数组values的下标顺序依次显示。
2.path:可以设置CGPathRef、CGMutablePathRef,让图层按照路径(path)轨迹移动。path只对CALayer的anchorPoint和position起作用。-(注)如果设置了path,那么values将被忽略。
3.keyTimes:可以为对应的关键侦指定对应的时间点,取值范围在1.0--0;keyTimes中的每一个时间值都对应values中的没一帧。如果没有设置keyTimes,各个关键祯的时间是平分的。(注)CABasicAnimation可看做是只有俩个关键祯的CAKeyframeAnimation
说了这么多,跟废话差不多,还是上代码吧。
#pragma makr - Values
#import "ViewController.h"
@interface ViewController () {
UIImageView *_imgView;
}
@end
/*------------------关键帧动画----------------------*/
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//这些勒色就不用介绍了吧---哈哈
_imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
_imgView.image = [UIImage imageNamed:@"024.png"];
[self.view addSubview:_imgView];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//获取手指点击的坐标
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
//创建动画对象
CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//设置动画属性
//设置时长
keyFrameAnimation.duration = 1;
CGPoint p1 = _imgView.center;
CGPoint p2 = CGPointMake(355, 20);
//CGPoint -》NSValue 设置三个移动的点。
NSValue *value1 = [NSValue valueWithCGPoint:p1];
NSValue *value2 = [NSValue valueWithCGPoint:p2];
NSValue *value3 = [NSValue valueWithCGPoint:touchPoint];
//将三个点放进values,动画会一次 从value1的位置移动到value2的位置,最后是移动到手指点击的位置。
keyFrameAnimation.values = @[value1,value2,value3];
//设置动画完毕时以动画的形式返回愿状态
keyFrameAnimation.autoreverses = YES;
//添加动画
[_imgView.layer addAnimation:keyFrameAnimation forKey:nil];
}
从图片最开始的位置移动到右上角,然后移动到你手机点击的地方
#pragma makr - Path
我们知道如果是简单的三角形运动,矩形运动,我们用上面的做法很容易实现,但是如果我们是画园呢。难道也要通过确定点,来做动画吗?很显然那样有点赘余了,那么我们换一种角度去思考。通过-------------路径
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//获取手指点击的坐标
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
//以手指点击的地方作为圆心,150作为半径的圆运动
//创建动画对象
CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//设置属性
keyFrameAnimation.duration = 2;
keyFrameAnimation.repeatCount = MAXFLOAT;
//设置运动的路径
CGMutablePathRef path = CGPathCreateMutable();
//画圆。
CGPathAddArc(path, NULL, touchPoint.x, touchPoint.y, 150, 0, M_PI*2, 1);
//把圆的路径给path
keyFrameAnimation.path = path;
//释放路径 ----上面用了<span style="font-family: Arial, Helvetica, sans-serif;">Create必须释放</span>
CGPathRelease(path);
//添加动画
[_imgView.layer addAnimation:keyFrameAnimation forKey:nil];
}
效果图,也不好展示。点击屏幕的点(圆心)150为半径画圆。大概也能想想出来吧。