Search code examples
xcodecore-graphicsclipping

core graphics CGContextClip - Xcode


Starting to understand core graphics. I'm drawing a path with a fill and a stroke, but I cannot get it to clip. Can anyone tell me what I am doing wrong here?

This code is in the drawRect method of my UIView sub class.

//Draw a closed path with rounded corners, a fill and a stroke.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);
CGContextSetStrokeColorWithColor(context,[UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
//fill
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextFillPath(context);
//stroke
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextStrokePath(context);
CGContextBeginPath(context);
//clip??
CGContextMoveToPoint(context, 10, 10);
CGContextAddLineToPoint(context, 10, 100);
CGContextAddArcToPoint(context, 10,140, 30,140, 20);
CGContextAddLineToPoint(context, 200, 140);
CGContextAddArcToPoint(context, 240,140, 240,100, 20);
CGContextAddLineToPoint(context, 240, 10);
CGContextClosePath(context);
CGContextClip(context);

Solution

  • You should use CGContextClip before CGContextStrokePath and after CGContextClosePath. That's enough. No need to write extra code. Try like this as following as..

        CGContextClosePath(context);
        CGContextClip(context);
        CGContextStrokePath(context);
    

    I think it will be helpful to you.