2012-10-07 86 views
5

我試圖實現一個iOS相機視圖,它採用正方形(類似於Instagram)的圖片。我的代碼出現在下面。第一部分,框架高度設置爲等於框架寬度,按預期工作,併爲用戶提供正方形的視圖。當我嘗試使用CGImageCreateWithImageInRect將框架(這是CGRect屬性)應用於圖像數據時,稍後會出現此問題。我將這個幀rect傳遞給這個圖像的方法。但結果並不是平方米。相反,圖像保留iOS相機的原始默認尺寸。有人可以告訴我我做錯了什麼嗎?我從Apple文檔中瞭解到,CGImageCreateWithImageInRect應該從某個起始x/y座標中選擇一個形狀爲Rect的圖像區域。但是這似乎並沒有發生。使用CGImageCreateWithImageInRect裁剪圖像

//Set the frame size to be square shaped 
UIView *view = imagePicker.view; 
     frame = view.frame; 
     frame.size.height = frame.size.width; 
     view.frame = frame; 

//Crop the image to the frame dimensions using CGImageCreateWithImageInRect 
-(void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    [self.popoverController dismissPopoverAnimated:true]; 

NSString *mediaType = [info 
         objectForKey:UIImagePickerControllerMediaType]; 
[self dismissModalViewControllerAnimated:YES]; 
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) { 
    UIImage *image = [info 
         objectForKey:UIImagePickerControllerOriginalImage]; 

    croppedImage = (__bridge UIImage *)(CGImageCreateWithImageInRect((__bridge CGImageRef)(image), frame)); 

    imageView.image = croppedImage; 

} 
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) 
{ 
    // Code here to support video if enabled 
} 
} 

回答

0

你是對的。唯一的事情是我認爲你將框架屬性設置爲與拾取器視圖相同,所以最終尺寸與原始尺寸相同。

嘗試設置框架比pickerView.view.frame小,不等於

檢查了這一點

Cropping an UIImage

+0

我試着通過一個任意小的CGRect,但輸出有0字節的圖像數據。我用CGRect rect = CGRectMake(0,26,50,50);.此外,我的原始代碼將幀高設置爲等於寬度,因此比原始尺寸更小。它基本上是一個基於iPhone屏幕尺寸的320x320正方形。 – hughesdan

+0

也許這個答案可以幫助http://stackoverflow.com/a/10185736/1447414 – user1447414