Search code examples
iosobjective-ccalayer

How to change color of CALayer while animating


I have an arc that goes around in a circle and changes colors three times. I used an example on SO to get me started: Change CALayer color while animating

This example works, however the colors are red, then green then blue. I would like them to be Green, Orange, then Red. I'm trying to figure out how in the code he changed colors, and it's quite confusing to me:

for (NSUInteger i = 0; i < 3; i++)
        {
            CAShapeLayer* strokePart = [[CAShapeLayer alloc] init];
            strokePart.fillColor = [[UIColor clearColor] CGColor];
            strokePart.frame = tutorialCircle.bounds;
            strokePart.path = tutorialCircle.path;
            strokePart.lineCap = tutorialCircle.lineCap;
            strokePart.lineWidth = tutorialCircle.lineWidth;

            // These could come from an array or whatever, this is just easy...
            strokePart.strokeColor = [[UIColor colorWithHue: i * portion saturation:1 brightness:1 alpha:1] CGColor];

So I believe this line is doing the color change:

strokePart.strokeColor = [[UIColor colorWithHue: i * portion saturation:1 brightness:1 alpha:1] CGColor];

My goal is to manipulate those colors to Green Orange Red instead of Red Green and Blue.

Thanks

EDIT:

This is the value of portion:

const double portion = 1.0 / ((double)3);

Solution

  • The HUE-Color system defines the color in a an angle of 360 degrees, where 0 is red, 108 (360*0,3) is a green and is a blue. This is how the colors get generated:

    strokePart.strokeColor = [[UIColor colorWithHue: 0 saturation:1 brightness:1 alpha:1] CGColor]; // RED
    
    strokePart.strokeColor = [[UIColor colorWithHue: 0.3 saturation:1 brightness:1 alpha:1] CGColor]; // GREEN
    
    strokePart.strokeColor = [[UIColor colorWithHue: 0.6 saturation:1 brightness:1 alpha:1] CGColor]; // BLUE
    

    If you want to change to colors, you could shift the portion by some other value:

    strokePart.strokeColor = [[UIColor colorWithHue: 0.3 + portion saturation:1 brightness:1 alpha:1] CGColor];
    

    Or you could define yourself an array, with your colors you want to go through:

    NSArray* colors = @[ UIColor.green, UIColor.orange, UIColor.red ];
    for (id color in colors)
        {
            CAShapeLayer* strokePart = [[CAShapeLayer alloc] init];
            strokePart.fillColor = [[UIColor clearColor] CGColor];
            strokePart.frame = tutorialCircle.bounds;
            strokePart.path = tutorialCircle.path;
            strokePart.lineCap = tutorialCircle.lineCap;
            strokePart.lineWidth = tutorialCircle.lineWidth;
    
            // These could come from an array or whatever, this is just easy...
            strokePart.strokeColor = [color CGColor];