Skip to content

Instantly share code, notes, and snippets.

@ha1f
Created June 20, 2018 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/52c13b4f7ddd3ff4a32aff27f7ec096d to your computer and use it in GitHub Desktop.
Save ha1f/52c13b4f7ddd3ff4a32aff27f7ec096d to your computer and use it in GitHub Desktop.
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