2013-04-25 28 views
4

我希望圖層從綠色開始,然後慢慢變成黃色,橙色,最後變成紅色。我該怎麼做呢?如何在動畫過程中更改CALayer的顏色?

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

回答

5

我剛剛爲你寫了這段代碼。我使用了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]; 
2

使用CAKeyframeAnimation是確定的,但有時你需要更簡單的東西。以下是使用CABasicAnimation和3行代碼的方法。

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

[layer addAnimation:colorAnimation forKey:nil];