How to flip UIImage horizontally with Swift?

46,699

Solution 1

Most factory methods are converted to initializers in swift. Whenever available, even if the class method is still available, they are preferred. You can use:

    init(CGImage cgImage: CGImage!, scale: CGFloat, orientation: UIImageOrientation)

The usage would look like this:

var image = UIImage(CGImage: img.CGImage, scale: 1.0, orientation: .DownMirrored)

Swift 5

var image = UIImage(cgImage: img.cgImage!, scale: 1.0, orientation: .downMirrored)

Solution 2

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 :)

Solution 3

In Swift.... (6.3.1)

YourUIImage.transform = CGAffineTransformMakeScale(-1, 1)

This also works with a UIView

Solution 4

Changing image orientation parameter is not actually flipping the image in all cases. Image must be redrawn somehow... For example like this:

Swift 3

func flipImageLeftRight(_ image: UIImage) -> UIImage? {

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    let context = UIGraphicsGetCurrentContext()!
    context.translateBy(x: image.size.width, y: image.size.height)
    context.scaleBy(x: -image.scale, y: -image.scale)

    context.draw(image.cgImage!, in: CGRect(origin:CGPoint.zero, size: image.size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}

Solution 5

Swift 4

YOURIMAGEVIEW.transform = CGAffineTransform(scaleX: -1, y: 1)
Share:
46,699
Lim Thye Chean
Author by

Lim Thye Chean

Virtual GS studio develops and publishes multimedia eBooks, retro games and children applications for iOS and Android devices.

Updated on July 24, 2022

Comments

  • Lim Thye Chean
    Lim Thye Chean almost 2 years

    The solution to do UIImage flipping is with the Objective-C code:

    [UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored]
    

    However, imageWithCGImage is not available in Swift! Is there a solution for flipping image horizontally with Swift? Thanks!