iosuiviewdrawrectcgcontextref

Different behaviours for different colors in drawRect:


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);
}

Solution

  • 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);