Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to rotate a UIImage 270 degrees clockwise in Swift 3?

Tags:

ios

swift

swift3

UIView.animate(withDuration:2.0, animations: {

         self.imageView.transform = CGAffineTransform(rotationAngle: (270 * CGFloat(2 * Double.pi)) / 360.0)
    })

This is animating anti clockwise i want the animation clockwise.

like image 934
Zubin Gala Avatar asked Dec 06 '22 13:12

Zubin Gala


1 Answers

To rotate by 270 degrees clockwise...

UIView.animate(withDuration:2.0, animations: {
            self.sampleView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
            self.sampleView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi * 3 / 2))
        })

Core Animation will always take the shortest route to make the rotation work. So, if your object is straight and you rotate to 90 degrees (radians: pi/2), it will rotate clockwise. If your object is straight and you rotate to 270 degrees (radians: pi + pi/2 = 3pi/2) it will rotate counter-clockwise because it's the smallest possible animation.

So we first need to rotate by pi radians (from 0 -> pi, 0 -> 180) then rotate by another pi/2 radians (pi -> 3pi/2, 180 -> 270) to perform the full rotation.

Notes :

  • To rotate by an angle greater than 180 degrees you need to perform 2 transforms, one for the first 180 degrees and then another for the rest.
  • To rotate by an angle greater than 360 degrees (like one and a half turns) you will need to perform three transforms.
  • To rotate by an odd angle, lets say 195 degrees, first rotate by 180 degrees then another 15 degrees.
  • While performing rotations you need to convert degrees to radians.
like image 155
NSAdi Avatar answered Mar 01 '23 23:03

NSAdi