How to draw multiple UIBezierPath with different colors in a UIView

iMacX picture iMacX · Jun 21, 2011 · Viewed 32.9k times · Source

I would like to draw multiple UIBezierPath in a UIView with different stroke and fill color.

Here is the code

- (void)drawRect:(CGRect)rect {

    context = UIGraphicsGetCurrentContext();

    [[UIColor grayColor] setFill]; 
    [[UIColor greenColor] setStroke];

    UIBezierPath *aPath = [[UIBezierPath alloc] init]; 
    [aPath moveToPoint:CGPointMake(227,34.25)];
    [aPath addLineToPoint:CGPointMake(298.25,34.75)];
    [aPath addLineToPoint:CGPointMake(298.5,82.5)];
    [aPath addLineToPoint:CGPointMake(251,83)];
    [aPath addLineToPoint:CGPointMake(251,67.5)];
    [aPath addLineToPoint:CGPointMake(227.25,66.75)];   
    [aPath closePath]; 
    aPath.lineWidth = 2;
    [aPath fill]; 
    [aPath stroke];

    UIBezierPath *aPath2 = [[UIBezierPath alloc] init];
    [aPath2 moveToPoint:CGPointMake(251.25,90.5)];
    [aPath2 addLineToPoint:CGPointMake(250.75,83.25)];
    [aPath2 addLineToPoint:CGPointMake(298.5,83)];
    [aPath2 addLineToPoint:CGPointMake(298.5,90.25)];
    [aPath2 closePath];
    aPath2.lineWidth = 2;
    [aPath2 fill]; 
    [aPath2 stroke];
    [paths addObject:aPath2];

The problem is that the stroke and the fill color are set on the current context. Is it possible to draw different UIBezierPath with different colors in the same CGContextRef?

Or I have to draw each UIBezierPath in separate UIView?

Answer

Deepak Danduprolu picture Deepak Danduprolu · Jun 21, 2011

You should add

[desiredStrokeColor setStroke];
[desiredFillColor setFill];

indicating that these are the new colors that have to used further on in this context. You should do this before every time you call a

[aNewPath fill];
[aNewPath stroke];

so that the paths be drawn with those colors.

No need to use a new view for each bezier path.