2016-03-01 35 views
1

我想在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()好像沒有什麼改變,我只是得到一個完整的純色背景(在這種情況下黑色。

回答

1

你想用的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

0

不同的方法,這可能是簡單的,是剛剛添加描邊的CAShapeLayer作爲視圖的maskLayer顯露出來,然後把顏色疊加視圖在其他視圖被屏蔽。因此,如果標記的視圖被遮罩,您的純色就會出現。