2016-05-02 37 views
0

如何爲UIBezier路徑的內部着色?我正在製作一個簡單的三角形,並想用紅色在三角形內部進行着色。在Swift中歸檔UIBezierPath

class GraphView : UIView { 

    override func drawRect(rect: CGRect) { 

     UIColor.redColor().setFill() 
     UIColor.greenColor().setStroke() 

     let path = UIBezierPath(rect: rect) 
     path.moveToPoint(CGPointMake(100,620)) 
     path.addLineToPoint(CGPointMake(300,100)) 
     path.addLineToPoint(CGPointMake(500,620)) 
     path.addLineToPoint(CGPointMake(100,620)) 

     path.closePath() 

     path.fill() 
     path.stroke() 

    } 

} 


let graphView = GraphView(frame: CGRectMake(0,0,960,640)) 
XCPlaygroundPage.currentPage.liveView = graphView 

上面的代碼寫在操場:下面是結果:

enter image description here

+0

奧普抱歉!用代碼和新屏幕截圖更新了問題。 –

回答

1

的問題是你如何創建UIBezierPath。您使用視圖邊界的矩形創建它,然後在該矩形內添加一個三角形。因此它們都被填滿了 - 導致整個視圖變成紅色。

如果設置usesEvenOddFillRuletrue,你會更清楚地看到你的路徑不需要的矩形的結果:

enter image description here

如果你只是想填補一個三角形中,那麼替換此行:

let path = UIBezierPath(rect: rect) 

與此:

let path = UIBezierPath() 

這會創建一個新的空的UIBezierPath您可以將三角形添加到。

+0

謝謝!有一點讓我感到困惑的是,即使我省略了最後一行:path.addLineToPoint(CGPointMake(100,620)),它仍然會創建三角形。它不需要最後一行來完成三角形。 –

+1

@johndoe'path.closePath()'會通過將路徑的最後一個點與路徑的第一個點(用直線)連接來創建三角形 - 因此,最後一行確實是多餘的。還要注意''path.fill()'會[隱式關閉路徑](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIBezierPath_class/#//apple_ref/occ/instm/UIBezierPath /填)。 – Hamish