在drawRect中绘制透明的UIBezierPath线 [英] Draw transparent UIBezierPath line inside drawRect
问题描述
我正在尝试在drawRect方法中实现透明路径。这是我创建的简单代码:
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()
}
这是结果:
有没有一种方法可以保持背景稳定,但路径线是透明的。如果我将第二行更改为 UIColor.clearColor()。set()
似乎什么也没发生,我只会得到完整的纯色(在这种情况下为黑色)。
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.
推荐答案
您要使用 kCGBlendModeDestinationOut
(以及纯色笔画)。
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)
其中...
-
R是预乘结果。
R is the premultiplied result.
S是源颜色,包括alpha
S is the source color, and includes alpha
D是目标颜色,包括alpha
D is the destination color, and includes alpha
Ra,Sa和Da是R,S和D的alpha分量
Ra, Sa, and Da are the alpha components of R, S, and D
这样,当使用纯色笔触颜色时,绘制的路径将是透明的。
clearColor $ c的原因$ c>对您不起作用是因为默认的混合模式是 additive ,因此所生成的颜色将不受绘制alpha
0 的颜色的影响。 code>。另一方面,
DestinationOut
是减法。
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.
因此,想要执行以下操作:
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
}
注意:
您必须设置 opaque
属性视图的 false
起作用,否则UIKit会假定它具有不透明的内容。例如:
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
}
这篇关于在drawRect中绘制透明的UIBezierPath线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!