Using NSBezierPath addClip - How to invert clip

1.2k views Asked by At

Using NSBezierPath addClip only limits drawing to inside the path used for clipping. I'd like to do the opposite - Only draw outside.

- (void)drawRect:(NSRect)dirtyRect {
    NSBezierPath *dontDrawInThis = ...;

    //We want an opposite mask of [dontDrawInThis setClip];

    //Drawing comes here
}
2

There are 2 answers

2
Avishay Cohen On

This was my solution:

- (void)drawRect:(NSRect)dirtyRect {
    NSBezierPath *dontDrawInThis = ...;

    // The mask is the whole bounds rect, subtracted dontDrawInThis

    NSBezierPath *clip = [NSBezierPath bezierPathWithRect:self.bounds];
    [clip appendBezierPath:dontDrawInThis.bezierPathByReversingPath];
    [clip setClip];

    //Drawing comes here
}

For iOS replace NSRect with CGRect.

0
nteissler On

Swift version of @avishic's answer

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    let restrictedPath = NSBezierPath()

    // fill the restricted path with shapes/paths you want transparent...

    let fullRect = NSBezierPath(rect: self.bounds)
    fullRect.append(restrictedPath.reversed)
    fullRect.setClip()
    NSColor.blue.setFill()

    frame.fill()
}