Orange Orange - 2 months ago 55
Swift Question

Shape a triangle with UIView backed by CAShapeLayer

From the tutorial :

http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/
, i managed to create a triangle like :

enter image description here

class Triangle: UIView {
override func drawRect(rect: CGRect) {
let mask = CAShapeLayer()
mask.frame = self.layer.bounds

let width = self.layer.frame.size.width
let height = self.layer.frame.size.height

let path = CGPathCreateMutable()

CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, width, height)
CGPathAddLineToPoint(path, nil, width/2, height)
CGPathAddLineToPoint(path, nil, width, height)


mask.path = path
self.layer.mask = mask
}
}


But what i'm trying to achieve, is a triangle like :

enter image description here

How does one do this?

Answer

Use this path instead:

CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, width/2, height)
CGPathAddLineToPoint(path, nil, 0, 0)

full class:

class Triangle: UIView {
    override func drawRect(rect: CGRect) {
        let mask = CAShapeLayer()
        mask.frame = self.layer.bounds

        let width = self.layer.frame.size.width
        let height = self.layer.frame.size.height

        let path = CGPathCreateMutable()

        CGPathMoveToPoint(path, nil, 0, 0)
        CGPathAddLineToPoint(path, nil, width, 0)
        CGPathAddLineToPoint(path, nil, width/2, height)
        CGPathAddLineToPoint(path, nil, 0, 0)

        mask.path = path
        self.layer.mask = mask
    }
}