Different behaviours for different colors in drawRect:

64 Views Asked by At

I am puzzled by the way the following code works. It is expected to produce a black disk surrounded by a colored circle. It works fine with certain colors (as explained in the comments), but not with some others. Can anyone explain this misterious behaviour?

- (void)drawRect:(CGRect)rect
{
    CGRect rectangle; CGFloat shiftVal=2.0,lineWidth=3.0;
    rectangle.origin=CGPointMake(shiftVal, shiftVal);
    rectangle.size=self.frame.size;
    rectangle.size.width-=shiftVal*2;
    rectangle.size.height-=shiftVal*2;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextFillEllipseInRect(context, rectangle);

    CGContextSetLineWidth(context, lineWidth);

    const CGFloat *components = CGColorGetComponents([UIColor greenColor].CGColor); // Works as expected.
    //const CGFloat *components = CGColorGetComponents([UIColor darkGrayColor].CGColor); // No surrounding circle (instead of darkGray).
    //const CGFloat *components = CGColorGetComponents([UIColor lightGrayColor].CGColor); // Produces a greenish circle (instead of lightGray)
    // Draw the outer circle:
    CGContextSetRGBStrokeColor(context,
                               components[0],
                               components[1],
                               components[2],
                               components[3]);
    CGContextStrokeEllipseInRect(context, rectangle);
}
2

There are 2 best solutions below

1
On BEST ANSWER

Similar to this answer I am guessing that darkGrayColor and lightGrayColor both represent gray-sacle values rather tan rgba-values. And therefore dont have 4 comoponents but only 2.

You might want / have to use a different approach of setting the color:

CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
0
On

The problem is that

CGColorGetComponents([UIColor lightGrayColor].CGColor);

does not return the RGB values of 'light gray'. If you inspect its values in the debugger, you will see that it is an array of 0.6667, 1, 0, 0. These are the components in a gray-only color space.

You should use another function like CGContextSetStrokeColorWithColor or UIColor's setStroke method to set the color. They have the additional benefit of being shorter as well :)