Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of CALayer during animation?

I want the layer to start from green, then slowly to yellow, orange and finally red. How do I do this?

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];
like image 892
user299648 Avatar asked Feb 16 '23 17:02

user299648


2 Answers

I just wrote up this code for you. I used a CAKeyframeAnimation both because it allows for multiple toValues and because it allows more control over the animation.

//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];
like image 73
pasawaya Avatar answered Mar 05 '23 08:03

pasawaya


Using CAKeyframeAnimation is OK but sometimes you need something simpler. Here is how to do it using CABasicAnimation and 3 lines of code.

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

[layer addAnimation:colorAnimation forKey:nil];
like image 21
Rafa de King Avatar answered Mar 05 '23 08:03

Rafa de King