2

我正在开发一个使用 iPhone 前置摄像头的应用程序。当使用此相机拍摄图像时,iPhone 会水平旋转图像。我想把它镜像回来,以便能够保存它并像在 iPhone 屏幕上看到的那样显示它。

我在网上阅读了很多文档和很多建议,但我仍然很困惑。

经过我的研究和多次尝试,我发现该解决方案适用于保存和显示:

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

但这是盲目使用,我不明白做了什么。

我尝试使用 2 imageWithCGImage 将其镜像起来,然后将其旋转 180°,但出于任何神秘原因,这不起作用。

所以我的问题是:你能帮我写一个有效的优化方法,而且我能理解它是如何工作的。矩阵对我来说是一个黑洞......

4

1 回答 1

10

如果这个矩阵太神秘了,也许把它分成两个步骤更容易理解:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0, tempImageView.frame.size.height);
CGContextScaleCTM(context, 1, -1);

[tempImageView.layer renderInContext:context];

变换矩阵从头到尾应用。最初,画布向上移动,然后图像的 y 坐标全部取反:

            +----+
            |    |
            | A  |
+----+      o----+     o----+
|    |                 | ∀  |
| A  | -->         --> |    |
o----+                 +----+

      x=x         x=x
      y=y+h       y=-y

改变坐标的两个公式可以合二为一:

 x = x
 y = -y + h

您制作的 CGAffineTransformMake 代表了这一点。基本上,对于CGAffineTransformMake(a,b,c,d,e,f),它对应于

x = a*x + c*y + e
y = b*x + d*y + f

有关Core Graphics 中 2D 仿射变换的更多信息,请参阅http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_affine/dq_affine.html 。

于 2011-04-03T22:16:49.937 回答