Last active
October 5, 2017 11:37
-
-
Save jorgifumi/23d69e0a19296cc0e6ce13c570e0eac5 to your computer and use it in GitHub Desktop.
Image rotation helper
This file contains 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 { | |
var fixedOrientation: UIImage { | |
if (imageOrientation == UIImageOrientation.up) { | |
return self | |
} | |
var transform:CGAffineTransform = CGAffineTransform.identity | |
if (imageOrientation == UIImageOrientation.down | |
|| imageOrientation == UIImageOrientation.downMirrored) { | |
transform = transform.translatedBy(x: size.width, y: size.height) | |
transform = transform.rotated(by: CGFloat.pi) | |
} | |
if (imageOrientation == UIImageOrientation.left | |
|| imageOrientation == UIImageOrientation.leftMirrored) { | |
transform = transform.translatedBy(x: size.width, y: 0) | |
transform = transform.rotated(by: CGFloat.pi / 2) | |
} | |
if (imageOrientation == UIImageOrientation.right | |
|| imageOrientation == UIImageOrientation.rightMirrored) { | |
transform = transform.translatedBy(x: 0, y: size.height) | |
transform = transform.rotated(by: -CGFloat.pi / 2) | |
} | |
if (imageOrientation == UIImageOrientation.upMirrored | |
|| imageOrientation == UIImageOrientation.downMirrored) { | |
transform = transform.translatedBy(x: size.width, y: 0) | |
transform = transform.scaledBy(x: -1, y: 1) | |
} | |
if (imageOrientation == UIImageOrientation.leftMirrored | |
|| imageOrientation == UIImageOrientation.rightMirrored) { | |
transform = transform.translatedBy(x: size.height, y: 0) | |
transform = transform.scaledBy(x: -1, y: 1) | |
} | |
let ctx: CGContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), | |
bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0, | |
space: cgImage!.colorSpace!, | |
bitmapInfo: cgImage!.bitmapInfo.rawValue)! | |
ctx.concatenate(transform) | |
if (imageOrientation == UIImageOrientation.left | |
|| imageOrientation == UIImageOrientation.leftMirrored | |
|| imageOrientation == UIImageOrientation.right | |
|| imageOrientation == UIImageOrientation.rightMirrored | |
) { | |
ctx.draw(cgImage!, in: CGRect(x:0,y:0,width:size.height,height:size.width)) | |
} else { | |
ctx.draw(cgImage!, in: CGRect(x:0,y:0,width:size.width,height:size.height)) | |
} | |
let cgimg: CGImage = ctx.makeImage()! | |
let imgEnd: UIImage = UIImage(cgImage: cgimg) | |
return imgEnd | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment