Search code examples
iosswiftuibezierpath

Creating triangle view fails when not added to x: 0 and y: 0


This code works when the frame's x and y are 0, but fails when using different x and y's:

class Triangle: UIView {
    override func draw(_ rect: CGRect) {
        let path = UIBezierPath()
        let startX = self.center.x
        let startY: CGFloat = 0
        path.move(to: CGPoint(x: startX, y: startY))
        path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
        path.addLine(to: CGPoint(x: 0, y: self.bounds.height))
        path.close()
        UIColor.green.setStroke()
        path.stroke()
    }
}

import UIKit

class ViewController: UIViewController {
    @IBAction func animate(_ sender: UIButton) {
        let triangleView = Triangle(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
        triangleView.backgroundColor = .clear
        self.view.addSubview(triangleView)
    }
}

This works:

 let triangleView = Triangle(frame: CGRect(x: 0, y: 0, width: 30, height: 30))

When failing it looks like this:

enter image description here

Well that is one ugly triangle. Why does it works with x: 0 and y:0 and fails when using different floats there? How can I fix this?


Solution

  • replace let startX = self.center.x with let startX = self. bounds.width / 2