Skip to content

Instantly share code, notes, and snippets.

@norsez
Last active February 19, 2023 04:54
Show Gist options
  • Save norsez/e318d68f6a48786d35b3e7fd3b3a32ae to your computer and use it in GitHub Desktop.
Save norsez/e318d68f6a48786d35b3e7fd3b3a32ae 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
}
}
@seyoung-hyun
Copy link

@norsez Thanks your code :)
Can I use your code in my commercial app?
Please let me know how I can use the code for commercial distribution.

@norsez
Copy link
Author

norsez commented Mar 14, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment