Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flip UIImage horizontally?

Objective-C

UIImage* sourceImage = [UIImage imageNamed:@"whatever.png"];

UIImage* flippedImage = [UIImage imageWithCGImage:sourceImage.CGImage 
                                            scale:sourceImage.scale
                                      orientation:UIImageOrientationUpMirrored];

Swift

let flippedImage = myImage.withHorizontallyFlippedOrientation()

A very simple way you can achieve this is by creating a UIImageView instead of a UIImage and do the transform on UIImageView.

yourImageView.image =[UIImage imageNamed:@"whatever.png"];
yourImageView.transform = CGAffineTransform(scaleX: -1, y: 1); //Flipped

Hope this helps.


Vertical flip is often required to initialise OpenGL texture using glTexImage2d(...). The above proposed tricks do not actually modify image data and will not work in this case. Here is a code to do the actual data flip inspired by https://stackoverflow.com/a/17909372

- (UIImage *)flipImage:(UIImage *)image
{
    UIGraphicsBeginImageContext(image.size);
    CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(0.,0., image.size.width, image.size.height),image.CGImage);
    UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return i;
}

I have tried with imageFlippedForRightToLeftLayoutDirection, and creating a new UIImage with diferent orientations but at least this is the only solution I found for flipping my image

let ciimage: CIImage = CIImage(CGImage: imagenInicial.CGImage!)
let rotada3 = ciimage.imageByApplyingTransform(CGAffineTransformMakeScale(-1, 1))

As you can see in my playground it worked!! :) enter image description here

And the, of course, let finalImage = UIImage(CIImage: rotada3)