下面的代碼可以幫助你。
您應該通過以下方式獲得正確的cropFrame拳頭
-(CGRect)cropRectForFrame:(CGRect)frame
{
// NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit");
CGFloat widthScale = imageview.superview.bounds.size.width/imageview.image.size.width;
CGFloat heightScale = imageview.superview.bounds.size.height/imageview.image.size.height;
float x, y, w, h, offset;
if (widthScale<heightScale) {
offset = (imageview.superview.bounds.size.height - (imageview.image.size.height*widthScale))/2;
x = frame.origin.x/widthScale;
y = (frame.origin.y-offset)/widthScale;
w = frame.size.width/widthScale;
h = frame.size.height/widthScale;
} else {
offset = (imageview.superview.bounds.size.width - (imageview.image.size.width*heightScale))/2;
x = (frame.origin.x-offset)/heightScale;
y = frame.origin.y/heightScale;
w = frame.size.width/heightScale;
h = frame.size.height/heightScale;
}
return CGRectMake(x, y, w, h);
}
然後你需要調用此方法來獲取裁剪圖像
- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect
{
// you need to update scaling factor value if deice is not retina display
UIGraphicsBeginImageContextWithOptions(rect.size,
/* your view opaque */ NO,
/* scaling factor */ 2.0);
// stick to methods on UIImage so that orientation etc. are automatically
// dealt with for us
[image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
這可能是你的好來源:開源庫快速將圖像裁剪添加到iOS應用程序中](http://maniacdev.com/2011/10/open-source-library-to-add-image-cropping-into-an-ios-app-quickly/) – Lucien 2012-04-09 21:33:50
可能重複[圖像裁剪API爲iOS](http://stackoverflow.com/questions/7087435/image-cropping-api-for-ios) – NAlexN 2015-04-08 15:16:55