CABasicAnimation只能从一个数值(fromValue)到另一个数值(toValue),而关键帧动画可以通过构建数组来保存这些数值。
path:可以设置一个CGPathRef.CGMutablePathRef,让图层按照轨迹移动。path(路径)只对CALayer的anchorPoint和position起作用。如果设置了path,那么values将被忽略。
//沿矩形路径移动的动画效果
- (void)moveRect:(CGPoint)point {
CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//通过position来获得改变位置
keyFrame.duration = 10;
//速度控制函数
keyFrame.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];//进入减速,中间加速,出去减速
//创建路径
CGMutablePathRef path = CGPathCreateMutable();
// keyFrame.keyTimes = nsarry 分配时间
//绘制路径
CGRect rect = CGRectMake(_imgView.center.x, _imgView.center.y, point.x - _imgView.center.x, point.y - _imgView.center.y);
//得到他的rect的值(图片中心点得x,y,让点击的点得x-图片中间点得x,得到他们直接x的长度,y的长度)
CGPathAddRect(path, NULL, rect);//向路径中添加一个矩形,然后在图形环境上绘制这条路径。
keyFrame.path = path;
//release路径
CGPathRelease(path);//因为在是C接口的方法所以不受Arc控制
[_imgView.layer addAnimation:keyFrame forKey:nil];
}
//当前视图范围内随机移动的动画效果(十个随机点)。
- (void)moveToPoint:(CGPoint)point {
CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
NSMutableArray *values = [NSMutableArray array];
NSValue *startPoint = [NSValue valueWithCGPoint:_imgView.center];
[values addObject:startPoint];//第一针的位置
for (int i = 0; i < 10; i++) {
NSValue *pValue = [NSValue valueWithCGPoint:[self randomPoint]];
[values addObject:pValue];
}
keyFrame.values = values;//这是关键帧动画的属性,后面是一个数组,里面放的是每一个帧,
keyFrame.duration = 5;
[_imgView.layer addAnimation:keyFrame forKey:nil];
}
- (CGPoint)randomPoint {
CGFloat x = arc4random_uniform(CGRectGetWidth(self.view.bounds));//随机数
CGFloat y = arc4random_uniform(CGRectGetHeight(self.view.bounds));
return CGPointMake(x, y);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];//创建uitouch属性,接受屏幕触摸事件
CGPoint p = [touch locationInView:self.view];//当前点坐标
[touch preciseLocationInView: