Question

I want to animate strokeColor of CAShapeLayer, but in CABasicAnimation I have two value (from and to). Is it only two color support while animation is fire? For example, on start I have strokeColor = [UIColor blueColor].CGColor; then

CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"strokeColor"];
colorAnimation.duration            = 3.0; // "animate over 3 seconds or so.."
colorAnimation.repeatCount         = 1.0;  // Animate only once..
colorAnimation.removedOnCompletion = NO;   // Remain stroked after the animation..
colorAnimation.fillMode = kCAFillModeForwards;
colorAnimation.toValue   = (id)[UIColor redColor].CGColor;
colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

on half-way I have a dark purple color, but I need, for example, yellow color.

Is it possible to add custom gradient to CABasicAnimation?

Was it helpful?

Solution

I don't think you can do that with CABasicAnimation, but you can use a CAKeyframeAnimation to set intermediate values for your animation:

CAKeyframeAnimation *colorAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeColor"];
colorAnimation.values               = @[(id)[[UIColor blueColor] CGColor],
                                        (id)[[UIColor yellowColor] CGColor],
                                        (id)[[UIColor redColor] CGColor]];
colorAnimation.duration             = 3.0;  // "animate over 3 seconds or so.."
colorAnimation.repeatCount          = 1.0;  // Animate only once..
colorAnimation.removedOnCompletion  = NO;   // Remain stroked after the animation..
colorAnimation.fillMode             = kCAFillModeForwards;
colorAnimation.timingFunction       = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

If you want a "across the spectrum" sort of feel, you could do:

colorAnimation.values = @[(id)[[UIColor blueColor] CGColor],
                          (id)[[UIColor greenColor] CGColor],
                          (id)[[UIColor yellowColor] CGColor],
                          (id)[[UIColor orangeColor] CGColor],
                          (id)[[UIColor redColor] CGColor]];

Or if you want more of a simple blue to red, but avoiding that really dark purple, you could do:

colorAnimation.values = @[(id)[[UIColor blueColor] CGColor],
                          (id)[[UIColor colorWithRed:0.9 green:0.0 blue:0.9 alpha:1.0] CGColor],
                          (id)[[UIColor redColor] CGColor]];

Lots of options.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top