【问题标题】:iPhone - flipping a UIImageiPhone - 翻转 UIImage
【发布时间】:2011-07-28 19:33:11
【问题描述】:

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

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

【问题讨论】:

    标签: iphone graphics camera flip mirror


    【解决方案1】:

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

    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

    【讨论】:

    • 该死的。好的,非常感谢,但我真的一个字都不懂 :-) 我想我必须非常努力才能做一些图形。但是有一个问题:为什么,如果我在最后一行(甚至第一行)使用 CGContextRotateCTM (context, 3.14) 将图像放在原始屏幕视图中,会返回一个空/透明图像?
    猜你喜欢
    • 2012-03-28
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多