#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];
}