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?
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; }
The CTM affects future drawing; you're capturing what you have already drawn. You need to concat that transformation before you draw, not after.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With