john doe john doe - 7 months ago 19
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) {

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


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

enter image description here

Answer

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.

Comments