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;
}