2014-09-26 104 views
0

我正在使用相機(iOS 7,iPad mini)拍攝照片並將其裁剪爲正方形。我非常滿意從以下代碼中獲得的默認裁剪功能:用相機拍攝的iOS裁剪圖像

imagePickerController = [[UIImagePickerController alloc] init]; 
    imagePickerController.delegate = self; 
    imagePickerController.mediaTypes = @[(NSString *) kUTTypeImage]; 
    imagePickerController.allowsEditing = YES; 
    UIImage *image = info[UIImagePickerControllerEditedImage] 

它給了我一個平方疊加在我拍攝的圖像上。如果我放大,我可以將圖像平移一下。不過,我很驚訝,我無法上下移動圖像(沒有縮放),將裁剪矩形移到圖像上。如果我嘗試這樣做,它就會彈回到原來的位置。我錯過了什麼?還是僅僅缺少這個功能?

從這裏的許多問題來看,大多數人的回答都令人失望,「必須以自定義的方式完成」。

+0

是的,我有我的應用程序相同的情況下 – 2014-09-26 11:04:08

回答

0

這是最簡單的方法(不需要重新實現UIImagePickerController)。首先,使用覆蓋圖使相機區域呈現正方形。這裏有一個例子3.5" 屏幕(你需要更新它爲iPhone 5的工作):

UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 
imagePickerController.sourceType = source; 

if (source == UIImagePickerControllerSourceTypeCamera) { 
    //Create camera overlay 
    CGRect f = imagePickerController.view.bounds; 
    f.size.height -= imagePickerController.navigationBar.bounds.size.height; 
    CGFloat barHeight = (f.size.height - f.size.width)/2; 
    UIGraphicsBeginImageContext(f.size); 
    [[UIColor colorWithWhite:0 alpha:.5] set]; 
    UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, barHeight), kCGBlendModeNormal); 
    UIRectFillUsingBlendMode(CGRectMake(0, f.size.height - barHeight, f.size.width, barHeight), kCGBlendModeNormal); 
    UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f]; 
    overlayIV.image = overlayImage; 
    [imagePickerController.cameraOverlayView addSubview:overlayIV]; 
} 

imagePickerController.delegate = self; 
[self presentViewController:imagePickerController animated:YES completion:nil]; 

然後,你會得到一張圖片後,從的UIImagePickerController回來,這作物的方形像這樣的東西。!。

//Crop the image to a square 
CGSize imageSize = image.size; 
CGFloat width = imageSize.width; 
CGFloat height = imageSize.height; 
if (width != height) { 
    CGFloat newDimension = MIN(width, height); 
    CGFloat widthOffset = (width - newDimension)/2; 
    CGFloat heightOffset = (height - newDimension)/2; 
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.); 
    [image drawAtPoint:CGPointMake(-widthOffset, -heightOffset) 
        blendMode:kCGBlendModeCopy 
         alpha:1.]; 
    image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
} 

這是目標C代碼

+0

感謝這個答案雖然我沒有實現它這個解決方案似乎工作,我卻不得不希望會有我缺少的默認解決方案。 – marqram 2014-11-05 14:06:55

相關問題