Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical flip of CGContext

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?

like image 336
teabot Avatar asked Jul 16 '09 05:07

teabot


2 Answers

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; }    
like image 146
benvolioT Avatar answered Sep 28 '22 17:09

benvolioT


The CTM affects future drawing; you're capturing what you have already drawn. You need to concat that transformation before you draw, not after.

like image 37
Peter Hosey Avatar answered Sep 28 '22 17:09

Peter Hosey