// 增加一个中间点 // 中心点用个随机点 // 1. 动画 CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; NSValue *p1 = [NSValue valueWithCGPoint:self.center]; NSValue *p2 = [NSValue valueWithCGPoint:[self randomPoint]]; NSValue *p3 = [NSValue valueWithCGPoint:to]; anim.values = @[p1, p2, p3]; anim.duration = 1.0f; anim.removedOnCompletion = NO; anim.fillMode = kCAFillModeForwards; anim.delegate = self; [self.layer addAnimation:anim forKey:nil];
下面是一个用帧动画做出摇动动画的demo
- (void)shake { // 1. 动画 CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"]; // 2. 设置角度 CGFloat angle = M_PI_4 / 10; anim.values = @[@(-angle), @(angle), @(-angle)]; anim.duration = 0.2f; anim.repeatCount = HUGE_VALF; [self.layer addAnimation:anim forKey:nil]; }
关键帧动画还可以沿着CGPath类型的路径进行动画
#pragma mark - 按照路径平移的关键帧动画 - (CAKeyframeAnimation *)moveWithPath:(CGPathRef)path duration:(NSTimeInterval)duration { // 1. 动画 CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; // 2. 设置路径 anim.path = path; // 3. 设置时长 anim.duration = duration; return anim; }
动画组是一组动画的合成,他可以合并多个动画,然后添加到图层上,让多个动画同时执行
下面是一个动画组的小demo
- (void)groupDemo { /** 群组动画可以将一组动画继承在一起,并发执行,产生更加复杂的动画效果 需要注意的是,群组中的动画,不能修改同一个keyPath */ // 实例化一个动画组 CAAnimationGroup *group = [[CAAnimationGroup alloc] init]; // 透明度动画 CABasicAnimation *alpha = [CABasicAnimation animationWithKeyPath:@"opacity"]; alpha.fromValue = @(1.0); alpha.toValue = @(0.5); // 旋转动画 CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; rotate.toValue = @(2 * M_PI); // 关键帧动画 CAKeyframeAnimation *keyAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; CGMutablePathRef path = CGPathCreateMutable(); CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 300)); keyAnim.path = path; // 释放路径 CGPathRelease(path); group.animations = @[alpha, keyAnim, rotate]; group.duration = 1.0f; [_myView.layer addAnimation:group forKey:nil]; }