Eugen Software Engineer

How to rotate a UIImage

While I was developing a camera related iOS app I noticed you don’t have swift support to rotate a UIImage, so I wrote a small and useful extension.

Code

import UIKit

extension UIImage {
  public func rotated(byDegrees degrees: CGFloat) -> UIImage? {
    let degreesToRadians: (CGFloat) -> CGFloat = {
      return $0 / 180.0 * CGFloat(M_PI)
    }

    let rotatedViewContainer = UIView(frame: CGRect(origin: .zero, size: size))
    rotatedViewContainer.transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
    let rotatedSize = rotatedViewContainer.frame.size
    
    UIGraphicsBeginImageContext(rotatedSize)
    if let bitmap = UIGraphicsGetCurrentContext() {
      bitmap.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
      bitmap.rotate(by: degreesToRadians(degrees))
      bitmap.scaleBy(x: 1.0, y: -1.0)
      bitmap.draw(self.cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
    }
    let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return rotatedImage
  }
}

Usage

To use it you just need to copy/paste it in your project and you’ll have a new method for every UIImage instance.

Assuming you have the extension in your project, just call .rotated(byDegrees: X) to get the rotated image.

guard let url = URL(string: "https://unsplash.it/300/200"),
  let imageData = try? Data(contentsOf: url),
  let originalImage = UIImage(data: imageData) else {
  fatalError("no image")
}
print(originalImage.size) // (300, 200)

if let rotatedImage = originalImage.rotated(byDegrees: 90) {
  print(rotatedImage.size) // (200, 300)

}

I’ve made the extension available on github: UIImage.rotated and will share it as a cocoapod soon.