Search code examples
iosswiftuibezierpathcashapelayer

Creating Triangle with UIBezierPath in Swift


I am trying to understand how to create a triangle shape with Swift. I found this code that creates a triangle.

class TriangleLayer: CAShapeLayer {

  let innerPadding: CGFloat = 30.0  

  override init() {
    super.init()
    fillColor = Colors.red.CGColor
    strokeColor = Colors.red.CGColor
    lineWidth = 7.0
    lineCap = kCALineCapRound
    lineJoin = kCALineJoinRound
    path = trianglePathSmall.CGPath
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  var trianglePathSmall: UIBezierPath {
     let trianglePath = UIBezierPath()
     trianglePath.moveToPoint(CGPoint(x: 5.0 + innerPadding, y: 95.0))     // #1
     trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5 + innerPadding)) // #2
     trianglePath.addLineToPoint(CGPoint(x: 95.0 - innerPadding, y: 95.0)) // #3
     trianglePath.closePath()
     return trianglePath
 }

And this code creates a shape like this enter image description here in the middle of the screen.

I tried to tweak and play around with it to understand how it works; however, at this point I realised that I got lost with the logic quite a bit. I placed the CGPoints of above triangle on an x-y axis in my head and it seems something like:

 #1 x:35, y:95          #3 x:65, y:95
           #2 x:50, y: 42.5 

But the triangle is created upside-down if I place the dots on the x-y axis.

enter image description here

What I want to achieve is what the axis tells, and I want to achieve..

         .   .                                .
                 <like this.   not this> 
           .                                .   .


Solution

  • You just have the axes in your head upside down. The coordinate system starts at 0,0 and extends right in X and down in Y.

    So your points are really:

               #2 x:50, y: 42.5 
     #1 x:35, y:95          #3 x:65, y:95
    

    to get your desired triangle you'd have something like:

     #1 x:35, y:95          #3 x:65, y:95
               #2 x:50, y: 147.5