动画组

动画组

CABasicAnimationCAKeyframeAnimation仅仅作用于单独的属性,而CAAnimationGroup可以把这些动画组合在一起。CAAnimationGroup是另一个继承于CAAnimation的子类,它添加了一个animations数组的属性,用来组合别的动画。我们把清单8.6那种关键帧动画和调整图层背景色的基础动画组合起来(清单8.10),结果如图8.3所示。

清单8.10 组合关键帧动画和基础动画

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. //create a path
  5. UIBezierPath *bezierPath = [[UIBezierPath alloc] init];
  6. [bezierPath moveToPoint:CGPointMake(0, 150)];
  7. [bezierPath addCurveToPoint:CGPointMake(300, 150) controlPoint1:CGPointMake(75, 0) controlPoint2:CGPointMake(225, 300)];
  8. //draw the path using a CAShapeLayer
  9. CAShapeLayer *pathLayer = [CAShapeLayer layer];
  10. pathLayer.path = bezierPath.CGPath;
  11. pathLayer.fillColor = [UIColor clearColor].CGColor;
  12. pathLayer.strokeColor = [UIColor redColor].CGColor;
  13. pathLayer.lineWidth = 3.0f;
  14. [self.containerView.layer addSublayer:pathLayer];
  15. //add a colored layer
  16. CALayer *colorLayer = [CALayer layer];
  17. colorLayer.frame = CGRectMake(0, 0, 64, 64);
  18. colorLayer.position = CGPointMake(0, 150);
  19. colorLayer.backgroundColor = [UIColor greenColor].CGColor;
  20. [self.containerView.layer addSublayer:colorLayer];
  21. //create the position animation
  22. CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animation];
  23. animation1.keyPath = @"position";
  24. animation1.path = bezierPath.CGPath;
  25. animation1.rotationMode = kCAAnimationRotateAuto;
  26. //create the color animation
  27. CABasicAnimation *animation2 = [CABasicAnimation animation];
  28. animation2.keyPath = @"backgroundColor";
  29. animation2.toValue = (__bridge id)[UIColor redColor].CGColor;
  30. //create group animation
  31. CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
  32. groupAnimation.animations = @[animation1, animation2];
  33. groupAnimation.duration = 4.0;
  34. //add the animation to the color layer
  35. [colorLayer addAnimation:groupAnimation forKey:nil];
  36. }

图8.3

图8.3 关键帧路径和基础动画的组合