OWolf
OWolf

Reputation: 5132

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

Upvotes: 0

Views: 3334

Answers (2)

Prasad G
Prasad G

Reputation: 6718

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.

Upvotes: 0

David Rönnqvist
David Rönnqvist

Reputation: 56625

You should clip the context before doing the drawings that should be clipped and then restore the context after

Upvotes: 1

Related Questions