2011-04-25 71 views
10

我正在寫一個iPhone應用程序,它使用AVFoundation拍攝照片並對其進行裁剪。 該應用類似於QR碼閱讀器:它使用帶覆蓋的AVCaptureVideoPreviewLayer。 覆蓋有一個正方形。我想裁剪圖像,以便裁剪後的圖像與用戶在廣場內的位置完全相同。由AVCaptureSession捕獲的裁剪圖像

預覽圖層具有重力AVLayerVideoGravityResizeAspectFill。

它看起來像相機實際捕獲的不完全是用戶在預覽圖層中看到的內容。這意味着我需要從預覽座標系移動到捕獲的圖像座標系,以便裁剪圖像。爲此,我認爲我需要以下參數: 1.視圖大小和捕獲的圖像大小之間的比例。 2.告知拍攝圖像的哪一部分與預覽圖層中顯示的內容相匹配的信息。

是否有人知道我如何獲得此信息,或者如果有不同的方法來裁剪圖像。 (p.s.捕獲預覽的屏幕截圖不是一個選項,據我所知可能導致應用程序被拒絕)。

預先感謝您

回答

5

希望這會符合您的要求

- (UIImage *)cropImage:(UIImage *)image to:(CGRect)cropRect andScaleTo:(CGSize)size { 
    UIGraphicsBeginImageContext(size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGImageRef subImage = CGImageCreateWithImageInRect([image CGImage], cropRect); 
    NSLog(@"---------");  
    NSLog(@"*cropRect.origin.y=%f",cropRect.origin.y); 
    NSLog(@"*cropRect.origin.x=%f",cropRect.origin.x); 

    NSLog(@"*cropRect.size.width=%f",cropRect.size.width);  
    NSLog(@"*cropRect.size.height=%f",cropRect.size.height);  

    NSLog(@"---------");  

    NSLog(@"*size.width=%f",size.width);  
    NSLog(@"*size.height=%f",size.height);  

    CGRect myRect = CGRectMake(0.0f, 0.0f, size.width, size.height); 
    CGContextScaleCTM(context, 1.0f, -1.0f); 
    CGContextTranslateCTM(context, 0.0f, -size.height); 
    CGContextDrawImage(context, myRect, subImage); 
    UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    CGImageRelease(subImage);  

    return croppedImage; 
} 
+0

它不會幫助因爲相機也會旋轉圖像。在這裏看到類似的問題http://cmgresearch.blogspot.co.il/2012/07/cropping-results-from.html – Dejell 2013-01-21 18:39:57

1

我想這是因爲這

- (CGRect)computeCropRect:(CGImageRef)cgImageRef 
{ 
    static CGFloat cgWidth = 0; 
    static CGFloat cgHeight = 0; 

    static CGFloat viewWidth = 320; 

    if(cgWidth == 0) 
     cgWidth = CGImageGetWidth(cgImageRef); 

    if(cgHeight == 0) 
     cgHeight = CGImageGetHeight(cgImageRef); 

    CGRect cropRect; 

    // Only based on width 
    cropRect.origin.x = cropRect.origin.y = kMargin * cgWidth/viewWidth; 
    cropRect.size.width = cropRect.size.height = kSquareSize * cgWidth/viewWidth; 

    return cropRect; 
} 

與kMargin和kSquareSize(20point和280point在我的情況只是簡單的)分別爲邊距和掃描區域

然後執行cro pping

CGRect cropRect = [self computeCropRect:cgCapturedImageRef]; 
CGImageRef croppedImageRef = CGImageCreateWithImageInRect(cgCapturedImageRef, cropRect);