Skip to content

Instantly share code, notes, and snippets.

@ha1f
Created June 20, 2018 07:40
Embed
What would you like to do?
extension UIImage {
/// CGAffineTransform to apply orientation of the image
var orientationTransformer: CGAffineTransform {
var transform = CGAffineTransform(translationX: size.width / 2, y: size.height / 2)
switch imageOrientation {
case .up, .upMirrored:
break
case .down, .downMirrored:
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.rotated(by: -CGFloat.pi / 2)
case .right, .rightMirrored:
transform = transform.rotated(by: CGFloat.pi / 2)
}
switch imageOrientation {
case .upMirrored, .downMirrored, .rightMirrored, .leftMirrored:
transform = transform.scaledBy(x: -1, y: 1)
default:
break
}
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
return transform.translatedBy(x: -size.height / 2, y: -size.width / 2)
case .up, .upMirrored, .down, .downMirrored:
return transform.translatedBy(x: -size.width / 2, y: -size.height / 2)
}
}
/// CGAffineTransform to revert orientation of the image
var inverseOrientationTransformer: CGAffineTransform {
var transform = CGAffineTransform.identity
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
transform = transform.translatedBy(x: size.height / 2, y: size.width / 2)
case .up, .upMirrored, .down, .downMirrored:
transform = transform.translatedBy(x: size.width / 2, y: size.height / 2)
}
switch imageOrientation {
case .upMirrored, .downMirrored, .rightMirrored, .leftMirrored:
transform = transform.scaledBy(x: -1, y: 1)
default:
break
}
switch imageOrientation {
case .up, .upMirrored:
break
case .down, .downMirrored:
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.rotated(by: CGFloat.pi / 2)
case .right, .rightMirrored:
transform = transform.rotated(by: -CGFloat.pi / 2)
}
return transform.translatedBy(x: -size.width / 2, y: -size.height / 2)
}
/// CGAffineTransform which converts coordinate of CGImage to coordinate of UIImage
var transformer: CGAffineTransform {
return orientationTransformer.scaledBy(x: 1 / scale, y: 1 / scale)
}
/// CGAffineTransform which converts coordinate of UIImage to coordinate of CGImage
var inverseTransformer: CGAffineTransform {
return CGAffineTransform(scaleX: scale, y: scale).concatenating(inverseOrientationTransformer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment