使用由CAShapeLayer支持的UIView形成三角形

时间:2016-09-20 03:54:08

标签: ios swift xcode cashapelayer

从教程:http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/,我设法创建了一个三角形,如:

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

但我想要实现的是一个三角形:

enter image description here

如何做到这一点?

1 个答案:

答案 0 :(得分:3)

请改用此路径:

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

全班:

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
    }
}
相关问题