Search code examples
iosobjective-cuiviewcore-graphicscgcontext

Can't apply specific CGColor to CGContextSetFillColor


- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIColor*aColor = [UIColor colorWithRed:2 green:191 blue:166 alpha:1];
    CGContextSetFillColorWithColor(context, aColor.CGColor);
    CGContextAddArc(context, rect.size.width/2, rect.size.height/2, rect.size.height/2, 0, 2*3.1415926, 0);
    CGContextDrawPath(context, kCGPathFill);
}

the code is used to draw a circle ,but [UIColor colorWithRed:2 green:191 blue:166 alpha:1]does't work while [UIColor blackColor] works properly.


Solution

  • Because + (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha function use a range of 0.0 to 1.0 for red green blue alpha attributes.

    Your code should be like that:

    - (void)drawRect:(CGRect)rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
        UIColor*aColor = [UIColor colorWithRed:(2.0 / 255.0) green:(191.0 / 255.0) blue:(166.0 / 255.0) alpha:1];
        CGContextSetFillColorWithColor(context, aColor.CGColor);
        CGContextAddArc(context, rect.size.width/2, rect.size.height/2, rect.size.height/2, 0, 2*3.1415926, 0);
        CGContextDrawPath(context, kCGPathFill);
    }