4

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?

Orange
  • 59
  • 2
  • 14

1 Answers1

4

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
    }
}
Moriya
  • 7,750
  • 3
  • 35
  • 53