The solution to do UIImage flipping is with the Objective-C code:
[UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored
Swift 5
If your use case requires saving the UIImage
after transforming, it will need to be drawn into a new CGContext
.
extension UIImage {
enum Axis {
case horizontal, vertical
}
func flipped(_ axis: Axis) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image {
let context = $0.cgContext
context.translateBy(x: size.width / 2, y: size.height / 2)
switch axis {
case .horizontal:
context.scaleBy(x: -1, y: 1)
case .vertical:
context.scaleBy(x: 1, y: -1)
}
context.translateBy(x: -size.width / 2, y: -size.height / 2)
draw(at: .zero)
}
}
}
For me the simplest way was to use the .withHorizontallyFlippedOrientation()
instance method of UIImage
as follows:
let flippedImage = straightImage.withHorizontallyFlippedOrientation()
Simple one-liners always make me happy :)
Swift 4
YOURIMAGEVIEW.transform = CGAffineTransform(scaleX: -1, y: 1)