After much trials and tribulations ive found a solution to the same problem you had. Ive looked at other similar problems here on StackOverflow but non has paned out. So the concept is as follows:
A clear procedure for CGContext
- Draw a red triangle
- CGContextBeginTransparencyLayer(context,nil)
- Draw a blue circle
- CGContextClearRect(context,bounds)//will now only clear graphics made after the CGContextBeginTransparencyLayer call was made
- Draw a yellow square
- CGContextEndTransparencyLayer(context)
Result: You will now have a red triangle and a yellow square in the view (the blue circle was removed)
NOTE: by using CGContextBeginTransparencyLayer and CGContextEndTransparencyLayer you avoid making a transparent hole that would extend through every graphic in the application context, which would be the case if you used CGContextClearRect without the TransparencyLayer procedure described above.
A working Swift Playground example:
import Cocoa
import XCPlayground
class A:Shape{
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
let nsctx:NSGraphicsContext/**/ = NSGraphicsContext.currentContext()!
let context/**/ = nsctx.CGContext
let path:CGMutablePathRef = CGPathCreateMutable();
let rectangle:CGRect = CGRectMake(0.0, 0.0,200.0, 200.0);
CGPathAddRect(path,nil, rectangle);
CGContextAddPath(context,path)
CGContextSetFillColorWithColor(context,NSColor.greenColor().CGColor)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
}
}
class B:Shape{
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
let nsctx:NSGraphicsContext/**/ = NSGraphicsContext.currentContext()!
let context/**/ = nsctx.CGContext//was graphicsPort
CGContextBeginTransparencyLayer(context, nil);
CGContextAddPath(context,CircleParser.circlePath(100,100,100))
CGContextSetFillColorWithColor(context,NSColor.purpleColor().CGColor)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextClearRect(context, NSMakeRect(0, 0, dirtyRect.width, dirtyRect.height))
CGContextAddPath(context,CircleParser.circlePath(60,60,50))
CGContextSetFillColorWithColor(context,NSColor.blueColor().CGColor)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextEndTransparencyLayer(context);
}
}
class Shape:FlippedView{
init() {
let frame = NSRect(x: 0, y: 0, width: 300, height: 300)
super.init(frame: frame)
}
/*
* Required by super class
*/
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class Container:FlippedView{
init() {
let frame = NSRect(x: 0, y: 0, width: 500, height: 500)
super.init(frame: frame)
//self.wantsLayer = true
}
/*
* Required by super class
*/
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class FlippedView:NSView {//Organizes your view from top to bottom
override var flipped:Bool {
get {
return true
}
}
}
let container = Container()
let a = A()
let b = B()
container.addSubview(a)
container.addSubview(b)
XCPlaygroundPage.currentPage.liveView = container