Vertical flip of CGContext

teabot picture teabot · Jul 16, 2009 · Viewed 27.7k times · Source

I have a UIView that I am trying to render into a UIImage using [CALayer renderInContext:]. However, I find that the resultant image is flipped vertically. I kind of expect this due to the different coordinate systems. However, I then try and flip the context back to normal with an affine transform - but it doesn't have any effect:

CGAffineTransform flipVertical = CGAffineTransformMake(
    1, 0, 0, -1, 0, imageContextHeight
);
CGContextConcatCTM(imageContext, flipVertical);
CGImageRef cgImage = CGBitmapContextCreateImage(imageContext);
UIImage* uiImage = [[UIImage imageWithCGImage:cgImage] retain];
CGImageRelease(cgImage);

What am I doing wrong?

Answer

benvolioT picture benvolioT · Jul 1, 2010

Here is some code that I wrote based on this answer, in case it is helpful to anyone:

#import <QuartzCore/QuartzCore.h>
...
+ (UIImage *) flipImageVertically:(UIImage *)originalImage {
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:originalImage];

    UIGraphicsBeginImageContext(tempImageView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform flipVertical = CGAffineTransformMake(
            1, 0, 0, -1, 0, tempImageView.frame.size.height
    );
    CGContextConcatCTM(context, flipVertical);  

    [tempImageView.layer renderInContext:context];

    UIImage *flipedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [tempImageView release];

    return flipedImage;
}