使用 CAShapeLayer 支持的 UIView 塑造一个三角形

Shape a triangle with UIView backed by CAShapeLayer

根据教程:http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/,我成功创建了一个三角形:

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
    }
}

但我想要实现的是像这样的三角形:

如何做到这一点?

改为使用此路径:

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

完整 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
    }
}