iPhone - flipping a UIImage
I'm working on an app that uses the front camera of the iPhone. When an image is captured with this camera, it is wirrored horizontally by the iPhone. I want to mirror it back to be able to save it and to display it as it was seen on the iPhone screen.
I've read lots of docs, and lots of advices on the net, and I'm still very confused.
After my researches and many tries, I've found that solution that works for both saving and displaying :
- (UIImage *) flipImageLeftRight:(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();
flipedImage = [UIImage imageWithCGImage:flipedImage.CGImage scale:1.0 orientation:UIImageOrientationDown];
UIGraphicsEndImageContext();
[tempImageView release];
return flipedImage;
}
But 开发者_StackOverflowit's a blind use and I don't understand what is done.
I tried to use 2 imageWithCGImage to mirror it up then rotate it by 180°, but this don"t work for any mysterious reason.
So my question is : could you help me to write an optimised method that works, and which I would be able to understand how it works. Matrix is a black hole for me...
If that matrix is too mysterious, perhaps separating it into two steps make it easier to understand:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, tempImageView.frame.size.height);
CGContextScaleCTM(context, 1, -1);
[tempImageView.layer renderInContext:context];
Transformation matrices are applied from first to last. Initially, the canvas is moved upward, and then the image's y-coordinates are all negated:
+----+
| |
| A |
+----+ o----+ o----+
| | | ∀ |
| A | --> --> | |
o----+ +----+
x=x x=x
y=y+h y=-y
The two formulae that changes the coordinates can be combined into one:
x = x
y = -y + h
The CGAffineTransformMake you have made represents this. Basically, for CGAffineTransformMake(a,b,c,d,e,f)
, it corresponds to
x = a*x + c*y + e
y = b*x + d*y + f
See http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_affine/dq_affine.html for more info about 2D affine transform in Core Graphics.
精彩评论