You want to draw the path with a blend mode of kCGBlendModeDestinationOut
(and a solid color stroke).
According to the docs, this blend mode does the following:
R = D*(1 - Sa)
Where...
R is the premultiplied result.
S is the source color, and includes alpha
D is the destination color, and includes alpha
Ra, Sa, and Da are the alpha components of R, S, and D
This way, when used with a solid stroke color, the drawn path will be 'transparent'.
The reason clearColor
won't work for you is because the default blend mode is additive, therefore the resultant color will be unaffected by the drawing a color with an alpha of 0
over it. DestinationOut
on the other hand is subtractive.
So you'll want to do something like the following:
override func drawRect(rect: CGRect) {
let clippingPath = UIBezierPath()
let context = UIGraphicsGetCurrentContext() // get your current context
// draw your background color
UIColor.greenColor().set();
CGContextFillRect(context, bounds)
CGContextSaveGState(context) // save the current state
CGContextSetBlendMode(context, .DestinationOut) // change blend mode to DestinationOut (R = D * (1-Sa))
// do 'transparent' drawing
UIColor.whiteColor().set();
clippingPath.moveToPoint(CGPoint(x: 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.addLineToPoint(CGPoint(x: CGRectGetWidth(self.bounds) - 10, y: CGRectGetHeight(self.bounds) / 2))
clippingPath.lineWidth = 6
clippingPath.lineCapStyle = .Round
clippingPath.stroke()
CGContextRestoreGState(context) // restore state of context
// do further drawing if needed
}
Note:
You'll have to set the opaque
property of the view to false
for this to work, otherwise UIKit will assume it has opaque contents. For example:
override init(frame: CGRect) {
super.init(frame: frame)
opaque = false
}