-
-
Save vukcevich/cb421b3c19866888d23d7c1fc8a04961 to your computer and use it in GitHub Desktop.
Rotate UIImage by radians in Swift 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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