2013-05-30 34 views
1

我有一個圖像視圖,顯示從相機或圖庫獲取的寬高比圖像。在Imageview的頂部,我放置了一個UIView(可移動,可伸縮)。在iOS應用程序中裁剪圖像

我想裁剪圖像的區域相對於該UIView的框架。

所以我這樣做:

CGImageRef imageRef = CGImageCreateWithImageInRect([myImageView.image CGImage], cropV.frame);// cropV is the UIview over the myImageView 

UIImage *img = [UIImage imageWithCGImage:imageRef]; 

CGImageRelease(imageRef); 

當我這樣做的問題是,我的矩形(UIView的)圖像(在尺寸大)上的實際位置是不一樣的。

例如, 對於1024x1024圖像,在320x480的屏幕 上以及我的cropV位於圖框(10,10,300,300)上時,圖像aoppear在方面適合模式下會有所不同; CGImageCreateWithImageInRect將根據1024x1024圖像創建圖像。

有沒有一種方法可以根據圖像大小縮放我的cropV幀?因此,矩形(cropV)只有那部分被裁剪。

現在我正在上下文中繪製圖像。但這給了我模糊的作物寬屏/良好的高清照片。

UIGraphicsBeginImageContext(myImageView.frame.size); 

[myImageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], cropV.frame); 

回答

0

您可以代表您的圖像和視圖獲取比例,然後製作您的矩形。

float ratio = yourImage.size.height/yourView.frame.size.height; 

試試這個

wRatio_width = myImageView.image.size.width/cropV.frame.size.width; 
wRatio_height = myImageView.image.size.height/cropV.frame.size.height; 
CGRect headImageRect = cropV.frame; 
headImageRect.origin.x=wRatio_width * headImageRect.origin.x; 
headImageRect.origin.y=wRatio_height * headImageRect.origin.y; 

headImageRect.size.width=wRatio_width * headImageRect.size.width; 
headImageRect.size.height=wRatio_height * headImageRect.size.height; 

cropV.frame=headImageRect; 
+0

無法弄清楚如何在我的環境中使用該!你是否建議,計算x,y,寬度和高度的比率,然後將我的cropV框架與這些值相乘 – Nil

+0

獲取與您的圖像(而不是UIImageView)和您的視圖有關的配給。 – Rajneesh071

+0

這樣做,但我得到完整的形象,而不是所需的作物區域。順便說一句,這是我做的,'wRatio = myImageView.image/cropV.frame.size.width;'然後將我的cropV廣度乘以比率。身高也一樣。 – Nil