在drawRect里面绘制透明的UIBezierPath行

问题描述:

我想在drawRect方法中实现一个透明的路径。这是一个简单的代码,我已经创建了:在drawRect里面绘制透明的UIBezierPath行

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() 
} 

这是结果:

enter image description here

有没有试图保持背景固体的方式,但是路径线透明。如果我改变第二行UIColor.clearColor().set()好像没有什么改变,我只是得到一个完整的纯色背景(在这种情况下黑色。

你想用的kCGBlendModeDestinationOut混合模式(与纯色行程绘制的路径。)

According to the docs,此混合模式执行以下操作:

R = d *(1 - 萨)

哪里..​​.

  • R是预乘的结果。

  • S是源色彩,并且包括阿尔法

  • d是目标的颜色,并且包括阿尔法

  • 镭,SA和DA的R,S,和d的alpha分量

这种方式,具有固体笔划颜色一起使用时,所绘制的路径将是“透明”。

原因clearColor不会为你工作是因为默认的混合模式为添加剂,因此产生的颜色会用的0在它的alpha绘制颜色的影响。另一方面,DestinationOut减法

所以你想要做的事像下面这样:

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会认为它有不透明的内容。例如:

override init(frame: CGRect) { 
    super.init(frame: frame) 
    opaque = false 
} 
+0

谢谢。我已经尝试过,但现在我得到了一条黑线。我已经在红色uiview的顶部添加了这个视图,期望看到一条红线,但它仍然显示为黑色 – Tomus85

+0

啊是的,我忘了提及你应该将'UIView'的'backgroundColor'设置为'clearColor '。然后你可以在'drawRect'中绘制你的背景颜色。这样做应该解决问题。 – Hamish

+0

我试过了,似乎没有修复它 – Tomus85

不同的方法,这可能是简单的,是刚刚添加描边的CAShapeLayer作为视图的maskLayer显露出来,然后把颜色叠加视图在其他视图被屏蔽。因此,如果标记的视图被遮罩,您的纯色就会出现。