Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut a rectangle out of an NSBezierPath

Is it possible to remove a chunk of NSBezierPath that is defined by an NSRect region within the path?

like image 279
Kristina Brooks Avatar asked Apr 15 '11 21:04

Kristina Brooks


2 Answers

As was noted in the comments, Mr. Caswell's answer is actually the opposite of what the OP was asking. This code sample shows how to remove a rect from a circle (or any bezier path from any other bezier path). The trick is to "reverse" the path that you want to remove, then append it to the original path:

NSBezierPath *circlePath = [NSBezierPath bezierPathWithOvalInRect:NSMakeRect(0, 0, 100, 100)];
NSBezierPath *rectPath = [NSBezierPath bezierPathWithRect:NSMakeRect(25, 25, 50, 50)];
rectPath = [rectPath bezierPathByReversingPath];
[circlePath appendBezierPath:rectPath];

Note: things get a little trickier if the bezier paths cross each other. Then you have to set the proper "winding rule".

like image 200
Roberto Avatar answered Oct 27 '22 21:10

Roberto


Absolutely. This is what clipping regions do:

// Save the current clipping region
[NSGraphicsContext saveGraphicsState];
NSRect dontDrawThisRect = NSMakeRect(x, y, w, h);
// Either:
NSRectClip(dontDrawThisRect);
// Or (usually for more complex shapes):
//[[NSBezierPath bezierPathWithRect:dontDrawThisRect] addClip];
[myBezierPath fill];    // or stroke, or whatever you do
// Restore the clipping region for further drawing
[NSGraphicsContext restoreGraphicsState];
like image 27
jscs Avatar answered Oct 27 '22 22:10

jscs