我正在使用以下裁剪方法来裁剪坐在UIImageView中的uiimage,然后UIImageView坐在UIScrollView中。
-(UIImage *)cropImage:(UIImage *)image
{
float scale = 1.0f/_scrollView.zoomScale;
NSLog(@"Oh and heres that zoomScale: %f", _scrollView.zoomScale);
CGRect visibleRect;
visibleRect.origin.x = _scrollView.contentOffset.x * scale;
visibleRect.origin.y = _scrollView.contentOffset.y * scale;
visibleRect.size.width = _scrollView.bounds.size.width * scale;
visibleRect.size.height = _scrollView.bounds.size.height * scale;
NSLog(@"Oh and here's that CGRect: %f", visibleRect.origin.x);
NSLog(@"Oh and here's that CGRect: %f", visibleRect.origin.y);
NSLog(@"Oh and here's that CGRect: %f", visibleRect.size.width);
NSLog(@"Oh and here's that CGRect: %f", visibleRect.size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], visibleRect);
UIImage *croppedImage = [[UIImage alloc] initWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
我需要将图像裁剪为(321,115)的CGSize。裁剪图像并查看打印结果后,我可以看到visibleRect是(0,0,321,115) - 它应该是什么,croppedImage
UIImage然后有宽度:321和高度:115。但出于某种原因,图像似乎完全放大了(该方法将原始图像的一小部分裁剪为321x115)。
为什么这种方法无法正确裁剪我的图像?
- 作为旁注:当我调用此方法时,我调用的方式是_croppedImage = [self cropImage:_imageView.image];
,它将自定义UIView类的UIImage属性设置为裁剪后的图像。
答案 0 :(得分:1)
请尝试此功能。它可能对你有帮助。
参数:
UIImage
CGSize (321,115)
或任何尺寸//裁剪图像 - 图像将从完整图像裁剪
- (UIImage *)cropImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
double ratio;
double delta;
CGPoint offset;
//make a new square size, that is the resized imaged width
CGSize sz = CGSizeMake(newSize.width, newSize.width);
//figure out if the picture is landscape or portrait, then
//calculate scale factor and offset
if (image.size.width > image.size.height) {
ratio = newSize.width / image.size.width;
delta = (ratio*image.size.width - ratio*image.size.height);
offset = CGPointMake(delta/2, 0);
}
else {
ratio = newSize.width / image.size.height;
delta = (ratio*image.size.height - ratio*image.size.width);
offset = CGPointMake(0, delta/2);
}
//make the final clipping rect based on the calculated values
CGRect clipRect = CGRectMake(-offset.x,
-offset.y,
(ratio * image.size.width) + delta,
(ratio * image.size.height) + delta);
//start a new context, with scale factor 0.0 so retina displays get
//high quality image
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
} else {
UIGraphicsBeginImageContext(sz);
}
UIRectClip(clipRect);
[image drawInRect:clipRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
仅裁剪图像的选定部分
请检查this link