是否有可能删除由路径内的NSRect
区域定义的NSBezierPath
块?
正如评论中所指出的,Caswell先生的回答实际上与OP的问题相反。这个代码示例展示了如何从圆中移除矩形(或从任何其他贝塞尔路径中移除任何贝塞尔路径)。诀窍是"反转"您想要删除的路径,然后将其附加到原始路径:
NSBezierPath *circlePath = [NSBezierPath bezierPathWithOvalInRect:NSMakeRect(0, 0, 100, 100)];
NSBezierPath *rectPath = [NSBezierPath bezierPathWithRect:NSMakeRect(25, 25, 50, 50)];
rectPath = [rectPath bezierPathByReversingPath];
[circlePath appendBezierPath:rectPath];
注意:如果贝塞尔路径相互交叉,事情会变得有点棘手。然后你必须设定合适的"绕线规则"。
当然。这就是剪辑区域的作用:
// 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];
根据Roberto的回答,我已经将代码更新为Swift 5。这将绘制一个100x100的红色圆圈,中间剪出一个60x60的矩形。
let path = NSBezierPath(ovalIn: NSRect(x: 0, y: 0, width: 100, height: 100))
let cutoutRect = NSBezierPath(rect: NSRect(x: 20, y: 20, width: 60, height: 60)).reversed
path.append(cutoutRect)
NSColor.red.setFill()
path.fill()