How can I rotate an UIImageView by 20 degrees?

44,759

Solution 1

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)

Solution 2

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)

Solution 3

Swift version:

let degrees:CGFloat = 20
myImageView.transform = CGAffineTransformMakeRotation(degrees * CGFloat(M_PI/180) )

Solution 4

Swift 4.0

imageView.transform = CGAffineTransform(rotationAngle: CGFloat(20.0 * Double.pi / 180))

Solution 5

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)
Share:
44,759

Related videos on Youtube

Thanks
Author by

Thanks

I like to play guitar. Sometimes I need to develop software. But I hate it ;) I mean... it sucks. It really does. Well, not always. Oh, and I think I'm the guy with the most questions here.

Updated on January 12, 2020

Comments

  • Thanks
    Thanks over 4 years

    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?

  • Thanks
    Thanks almost 15 years
    Thanks! And I really thought it's complicated, just because of the "transform matrix" ;)
  • Supertecnoboff
    Supertecnoboff almost 9 years
    This should be ticked, its the best answer by far!
  • Liam Bolling
    Liam Bolling over 8 years
    Degrees conversion is a really nice plus, this should be the best one!
  • Onur Tuna
    Onur Tuna almost 8 years
    The same code (except let) will work for objective-c too.
  • skg
    skg almost 5 years
    Absolutely the best!