I am trying to achieve a transparency path in the drawRect method. This is the simple code I have created:
override func drawRect(rect: CGRect) {
let clippingPath = UIBezierPath()
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()
}
And this is the result:
Is there a way of trying to keep the background solid but the path line transparent. If I change the second line to UIColor.clearColor().set()
nothing seems to happen, I just get a full solid background colour (in this case black.
A different approach, which might be simpler, is to just add the stroke's
CAShapeLayer
as amaskLayer
of the view to be revealed, and then put the color overlay in another view behind the view being masked. Thus, where ever the marked view is masked, your solid color would appear.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:
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 of0
over it.DestinationOut
on the other hand is subtractive.So you'll want to do something like the following:
Note:
You'll have to set the
opaque
property of the view tofalse
for this to work, otherwise UIKit will assume it has opaque contents. For example: