2011-04-03 91 views
2

我正在研究使用iPhone的前置攝像頭的應用程序。 當使用本相機拍攝圖像時,它會被iPhone水平迴轉。 我想將其鏡像回來,以便能夠保存並在iPhone屏幕上顯示它。iPhone - 翻轉UIImage

我讀過很多文檔,網上有很多建議,我還是很困惑。

我的研究和多次嘗試後,我發現,解決方案,爲儲蓄和展示工程:

- (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°,但是,這個不要「T工作的任何神祕的原因

所以我的問題是:能不能幫我寫一個優化方法的工作原理,我將能夠理解它是如何工作的。Matrix對我來說是一個黑洞...

回答

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 

約核芯顯卡2D仿射變換,更多信息請參見http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_affine/dq_affine.html

+0

該死的。好的,非常感謝你,但我真的不明白這個:-)我想我必須努力工作才能做一些圖形。但是一個問題:爲什麼如果我在最後一行(甚至是第一個)使用CGContextRotateCTM(上下文,3.14)將圖像置於原始屏幕視圖中,會返回一個空的/透明的圖像? – Oliver 2011-04-03 23:05:48