Skip to content

Instantly share code, notes, and snippets.

@Abhishek9634
Forked from norsez/UIImage+Rotation.swift
Created March 13, 2019 14:16
Show Gist options
  • Save Abhishek9634/ac636aea56f2907bc9fa8045a9572de1 to your computer and use it in GitHub Desktop.
Save Abhishek9634/ac636aea56f2907bc9fa8045a9572de1 to your computer and use it in GitHub Desktop.
Rotate UIImage by radians in Swift 3
extension UIImage {
func image(withRotation radians: CGFloat) -> UIImage {
let cgImage = self.cgImage!
let LARGEST_SIZE = CGFloat(max(self.size.width, self.size.height))
let context = CGContext.init(data: nil, width:Int(LARGEST_SIZE), height:Int(LARGEST_SIZE), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: cgImage.bitmapInfo.rawValue)!
var drawRect = CGRect.zero
drawRect.size = self.size
let drawOrigin = CGPoint(x: (LARGEST_SIZE - self.size.width) * 0.5,y: (LARGEST_SIZE - self.size.height) * 0.5)
drawRect.origin = drawOrigin
var tf = CGAffineTransform.identity
tf = tf.translatedBy(x: LARGEST_SIZE * 0.5, y: LARGEST_SIZE * 0.5)
tf = tf.rotated(by: CGFloat(radians))
tf = tf.translatedBy(x: LARGEST_SIZE * -0.5, y: LARGEST_SIZE * -0.5)
context.concatenate(tf)
context.draw(cgImage, in: drawRect)
var rotatedImage = context.makeImage()!
drawRect = drawRect.applying(tf)
rotatedImage = rotatedImage.cropping(to: drawRect)!
let resultImage = UIImage(cgImage: rotatedImage)
return resultImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment