4

我希望图层从绿色开始,然后慢慢变成黄色、橙色,最后变成红色。我该怎么做呢?

CAShapeLayer *layer = [CAShapeLayer layer];
[layer setStrokeColor:[UIColor greenColor].CGColor];
[layer setLineWidth:5.0f];
[layer setFillColor:[UIColor clearColor].CGColor];

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:button.bounds cornerRadius:10.0f];
layer.path = path.CGPath;

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat:1.0f];
animation.duration = 4.0f;

[layer addAnimation:animation forKey:@"myStroke"];
[button.layer addSublayer:layer];
4

2 回答 2

6

我刚刚为你编写了这段代码。我使用 CAKeyframeAnimation 既是因为它允许多个toValues动画,也是因为它允许对动画进行更多控制。

//Set up layer and add it to view
CALayer *layer = [CALayer layer];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];

//Create animation
CAKeyframeAnimation *colorsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"backgroundColor"];
colorsAnimation.values = [NSArray arrayWithObjects: (id)[UIColor greenColor].CGColor,
                          (id)[UIColor yellowColor].CGColor, (id)[UIColor orangeColor].CGColor, (id)[UIColor redColor].CGColor, nil];
colorsAnimation.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.25], [NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:0.75],[NSNumber numberWithFloat:1.0], nil];
colorsAnimation.calculationMode = kCAAnimationPaced;
colorsAnimation.removedOnCompletion = NO;
colorsAnimation.fillMode = kCAFillModeForwards;
colorsAnimation.duration = 3.0f;

//Add animation
[layer addAnimation:colorsAnimation forKey:nil];
于 2013-04-25T05:33:09.707 回答
2

使用CAKeyframeAnimation是可以的,但有时你需要一些更简单的东西。这是使用CABasicAnimation3 行代码的方法。

CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
colorAnimation.toValue = (id)[UIColor redColor].CGColor;

[layer addAnimation:colorAnimation forKey:nil];
于 2014-05-14T15:53:54.340 回答