Skip to content

Instantly share code, notes, and snippets.

@AmatsuZero
Created April 27, 2019 04:15
Show Gist options
  • Save AmatsuZero/09cd393d12651ce6cc43b5a48afc286a to your computer and use it in GitHub Desktop.
Save AmatsuZero/09cd393d12651ce6cc43b5a48afc286a to your computer and use it in GitHub Desktop.
extension UIImage {
func upFixedImage() -> UIImage? {
// No-op if the orientation is already correct
guard imageOrientation != .up else {
return nil
}
var transform = CGAffineTransform.identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: .pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: .pi / 2)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: -.pi / 2)
default:
break
}
switch imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
guard let cgImage = cgImage,
let colorSpace = cgImage.colorSpace,
let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0, space: colorSpace, bitmapInfo: cgImage.bitmapInfo.rawValue) else {
return nil
}
ctx.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
ctx.draw(cgImage, in: .init(origin: .zero, size: .init(width: size.height, height: size.width)))
default:
ctx.draw(cgImage, in: .init(origin: .zero, size: size))
}
// And now we just create a new UIImage from the drawing context
guard let ref = ctx.makeImage() else {
return nil
}
return UIImage(cgImage: ref)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment