views:

1624

answers:

2

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?

+5  A: 

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

Peter Hosey
A: 

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

+ (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;

}

benvolioT