ioscgcontextcgcontextref

Unable to set fill color in CGContext (CGContextSetFillColorWithColor)


Pardon me, but my knowledge of CGContext is fairly limited.

I am using the code from the accepted answer HERE to draw stars in a UIView. What I want to achieve is show the stars in 2 different colors (like a rating view). The problem is, I cannot seem to use 2 different colors for CGContextSetFillColorWithColor().

Relevant code:

if (i < 3) {

    NSLog(@"__BLACK__");

    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

} else {

    NSLog(@"__RED__");

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
}

Full code:

- (void) drawRect:(CGRect)rect {

    int aSize = 20;

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, aSize);

    CGFloat xCenter = 15.0;
    CGFloat yCenter = 12.5;

    float  w = 25.0;
    double r = w / 2.0;
    float flip = -1.0;

    for (NSUInteger i = 0; i < 5; i++) {

        if (i < 3) {

            NSLog(@"__BLACK__");

            CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
            CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

        } else {

            NSLog(@"__RED__");

            CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
            CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        }

        double theta = 2.0 * M_PI * (2.0 / 5.0); // 144 degrees

        CGContextMoveToPoint(context, xCenter, r * flip + yCenter);

        for (NSUInteger k = 1; k < 5; k++) {

            float x = r * sin(k * theta);
            float y = r * cos(k * theta);
            CGContextAddLineToPoint(context, x + xCenter, y * flip + yCenter);
        }
        xCenter += 37.5;
    }

    CGContextClosePath(context);
    CGContextFillPath(context);
}

On compilation and execution i get the log :

__BLACK__
__BLACK__
__BLACK__
__RED__
__RED__

However, the fill colors don't seem to take effect, and the result is:

enter image description here

I don't understand what I'm doing wrong here.


Solution

  • When you set the fill color for the context, it's used on every object in that context. In your case, all 5 stars are drawn inside the same context, so only the last color setting (red) persists.

    You can probably achieve what you want to achieve with 5 distinct CGPaths drawn in one context.