iPhone - 翻转 UIImage

标签 iphone graphics camera flip mirror

我正在开发一个使用 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°,但这由于任何神秘的原因不起作用。

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

最佳答案

如果这个矩阵太神秘,也许将其分成两个步骤会更容易理解:

CGContextRef context = UIGraphicsGetCurrentContext();

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

[tempImageView.layer renderInContext:context];

变换矩阵从头到尾应用。最初, Canvas 向上移动,然后图像的 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

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

关于iPhone - 翻转 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5532781/

相关文章:

ios - 如何在 UIView 中持续更新绘图

javascript - 如何在 paper.js 中为动态创建的圆分配半径值

java - 相机中止时应用程序崩溃

android - 相机不工作 - startPreview 失败

iphone - 自定义UITableViewCell在[super dealloc]上崩溃

iphone - 在没有 UITableView 的情况下使用 NSFetchedResultsController

iphone - 计算 NSString 中的单词数

java - 将小程序屏幕的一部分复制到图像中

java - 为什么不使用这种更简单的 Java 图形实现?

android - 如何获取相机拍摄的图像的Uri并将其存储到图库