49

What do I have to do, if I need to rotate a UIImageView? I have a UIImage which I want to rotate by 20 degrees.

The Apple docs talk about a transformation matrix, but that sounds difficult. Are there any helpful methods or functions to achieve that?

Buck Doyle
  • 6,333
  • 1
  • 22
  • 35
Thanks
  • 40,109
  • 71
  • 208
  • 322

8 Answers8

114

If you want to turn right, the value must be greater than 0 if you want to rotate to the left indicates the value with the sign "-". For example -20.

CGFloat degrees = 20.0f; //the value in degrees
CGFloat radians = degrees * M_PI/180;
imageView.transform = CGAffineTransformMakeRotation(radians);

Swift 4:

let degrees: CGFloat = 20.0 //the value in degrees
let radians: CGFloat = degrees * (.pi / 180)
imageView.transform = CGAffineTransform(rotationAngle: radians)
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
alexmorhun
  • 1,903
  • 2
  • 18
  • 23
93

A transformation matrix is not incredibly difficult. It's quite simple, if you use the supplied functions:

imgView.transform = CGAffineTransformMakeRotation(.34906585);

(.34906585 is 20 degrees in radians)


Swift 5:

imgView.transform = CGAffineTransform(rotationAngle: .34906585)
nevos
  • 907
  • 1
  • 10
  • 22
Ed Marty
  • 39,590
  • 19
  • 103
  • 156
10

Swift version:

let degrees:CGFloat = 20
myImageView.transform = CGAffineTransformMakeRotation(degrees * CGFloat(M_PI/180) )
Frank Eno
  • 2,581
  • 2
  • 31
  • 54
5

Swift 4.0

imageView.transform = CGAffineTransform(rotationAngle: CGFloat(20.0 * Double.pi / 180))
William Hu
  • 15,423
  • 11
  • 100
  • 121
2

Here's an extension for Swift 3.

extension UIImageView {

    func rotate(degrees:CGFloat){
        self.transform = CGAffineTransform(rotationAngle: degrees * CGFloat(M_PI/180))
      }  
    }

Usage:

myImageView.rotate(degrees: 20)
JP Aquino
  • 3,946
  • 1
  • 23
  • 25
1

This is an easier formatting example (for 20 degrees):

CGAffineTransform(rotationAngle: ((20.0 * CGFloat(M_PI)) / 180.0))
Alex Bailey
  • 793
  • 9
  • 20
1
_YourImageView.transform = CGAffineTransformMakeRotation(1.57);

where 1.57 is the radian value for 90 degree

Radix
  • 3,639
  • 3
  • 31
  • 47
-2

As far as I know, using the matrix in UIAffineTransform is the only way to achieve a rotation without the help of a third-party framework.

Marc W
  • 19,083
  • 4
  • 59
  • 71