john doe john doe - 2 years ago 118
Swift Question

Filing UIBezierPath in Swift

How can I color the inside of the UIBezier path? I am making a simple triangle and want to color inside of the triangle with red color.

class GraphView : UIView {

override func drawRect(rect: CGRect) {


let path = UIBezierPath(rect: rect)





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

The above code is written in the playground: Here is the result:

enter image description here

Answer Source

The problem is with how you're creating your UIBezierPath. You're creating it with a rectangle of the view's bounds, and then adding a triangle inside that rectangle. Therefore they're both getting filled – resulting in the entire view being red.

If you set usesEvenOddFillRule to true, you'll better see the result of the unwanted rectangle in your path:

enter image description here

If you just want to fill a triangle then replace this line:

let path = UIBezierPath(rect: rect)

with this:

let path = UIBezierPath()

This will create a new empty UIBezierPath that you can add your triangle to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download