#pragma mark - 沿曲线移动
- (void)moveCurve:(CGPoint)toPoint {
//1.创建动画对象
CAKeyframeAnimation *keyframe = [CAKeyframeAnimation animationWithKeyPath:@"position"];
[keyframe setDuration:2];
CGMutablePathRef path = CGPathCreateMutable();
//起始点
CGPoint startPoint = myView.center;
CGPoint cp1 = [self randomPoint];
CGPoint cp2 = [self randomPoint];
CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
//绘制曲线
CGPathAddCurveToPoint(path, NULL, cp1.x, cp1.y, cp2.x, cp2.y, toPoint.x, toPoint.y);
keyframe.path = path;
CGPathRelease(path);
[myView.layer addAnimation:keyframe forKey:nil];
}
- (void)moveQuadCurve:(CGPoint)p {
//1.创建动画对象
CAKeyframeAnimation *keyframe = [CAKeyframeAnimation animationWithKeyPath:@"position"];
[keyframe setDuration:2];
CGMutablePathRef path = CGPathCreateMutable();
//起始点
CGPoint startPoint = myView.center;
//移动到路径的起始点
CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
//随机产生一个控制点
CGPoint top = [self randomPoint];
//绘制曲线
CGPathAddQuadCurveToPoint(path, NULL, top.x, top.y, p.x, p.y);
keyframe.path = path;
CGPathRelease(path);
[myView.layer addAnimation:keyframe forKey:nil];
}
#pragma mark - 沿矩形路径移动
- (void)moveRect:(CGPoint)p {
//1.创建动画对象
CAKeyframeAnimation *keyframe = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//时长
keyframe.duration = 2;
//2.创建路径
CGMutablePathRef path = CGPathCreateMutable();
CGFloat w = p.x - myView.center.x;
CGFloat h = p.y - myView.center.y;
//3.绘制路径
CGRect rect = CGRectMake(myView.center.x, myView.center.y, w, h);
CGPathAddRect(path, NULL, rect);
//4.将路径添加给动画
[keyframe setPath:path];
//5.是否路径
CGPathRelease(path);
//将动画添加到图层
[myView.layer addAnimation:keyframe forKey:nil];
}
//随机移动
- (void)moveRandom {
//1.创建动画对象
CAKeyframeAnimation *keyframe = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//2.设置动画属性
//1>时长
[keyframe setDuration:3];
NSMutableArray *values = [NSMutableArray array];
//定义起始点
NSValue *startPoint = [NSValue valueWithCGPoint:myView.center];
[values addObject:startPoint];
//随机产生多个点
for (int i=0; i<10; i++) {
CGPoint p = [self randomPoint];
NSValue *pValue = [NSValue valueWithCGPoint:p];
[values addObject:pValue];
}
//设置values
keyframe.values = values;
[myView.layer addAnimation:keyframe forKey:nil];
}
//移动到触摸点
- (void)moveToPoint:(CGPoint)p {
//1.创建动画对象
CAKeyframeAnimation *keyframe = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//2.定义动画属性
//1> values
NSValue *p1 = [NSValue valueWithCGPoint:myView.center];
NSValue *p2 = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
//触摸点的位置
NSValue *p3 = [NSValue valueWithCGPoint:p];
NSArray *values = @[p1,p2,p3];
//1>.设置多个值
keyframe.values = values;
//2>.设置动画时长
[keyframe setDuration:.01];
//3>.设置动画对象的代理对象,用于监听动画的结束事件
keyframe.delegate = self;
// keyframe.autoreverses = YES;
//3.添加动画
[myView.layer addAnimation:keyframe forKey:nil];
}