Search code examples
iosswiftrotationcore-graphicscore-animation

Swift: Trying to rotate a drawn shape?


I'm having trouble trying to rotate the shape I have drawn in the following code: I tried using:

triangle.transform = triangle.transform.rotated(by: 3.14159)

but that gives me an error of "value of type 'CATransform3D' has no member 'rotated'". I'm not sure how to rotate the shape.

override func viewDidLoad() {
    super.viewDidLoad()
    let trianglePath = UIBezierPath()
    trianglePath.move(to: CGPoint(x: UIScreen.main.bounds.size.width * 0.5, y: UIScreen.main.bounds.height * 0.5))
    trianglePath.addLine(to: CGPoint(x: (UIScreen.main.bounds.size.width * 0.5) + 100, y: (UIScreen.main.bounds.height * 0.5) - 50))
    trianglePath.addLine(to: CGPoint(x: (UIScreen.main.bounds.size.width * 0.5) + 100, y: (UIScreen.main.bounds.height * 0.5) + 50))
    trianglePath.close()

    let triangle = CAShapeLayer()
    triangle.path = trianglePath.cgPath
    triangle.fillColor = UIColor.gray.cgColor
    self.view.layer.addSublayer(triangle)
}

Solution

  • Use this to rotate your triangle, you can use use CGAffineTransform

     triangle.setAffineTransform(CGAffineTransform(rotationAngle: .pi))
    

    or using CATransform3D, rotating in Z axis by pi

     triangle.transform = CATransform3DMakeRotation(.pi, 0, 0, 1)
    

    but to this work you need to adjust also your CAShapeLayer frame

     triangle.frame = self.view.bounds //this do the trick
    

    For animate after it shows

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 0.1) { 
              triangle.setAffineTransform(CGAffineTransform(rotationAngle: .pi)) //this 
              triangle.transform = CATransform3DMakeRotation(.pi, 0, 0, 1) //or this
        }
    }
    

    Hope this helps