当我们直接使用CGImageCreateWithImageInRect获取图片时,会发现我们实际得到的截取图像,恰好是当rect旋转90°时,应该得到的图像:
- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage,rect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
return result;
这是因为CGImageCreateWithImageInRect中得rect是获取自UIImage中得rect,而不是UIImageView的;而在UIImage的坐标系中,(0,0)点位于左下角,因此在裁剪区域确定时,需要转换成对应坐标系中得区域:以下是转换代码:
- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect {
CGFloat (^rad)(CGFloat) = ^CGFloat(CGFloat deg) {
return deg / 180.0f * (CGFloat) M_PI;
};
// determine the orientation of the image and apply a transformation to the crop rectangle to shift it to the correct position
CGAffineTransform rectTransform;
switch (image.imageOrientation) {
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
// adjust the transformation scale based on the image scale
rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale);
// apply the transformation to the rect to create a new, shifted rect
CGRect transformedCropSquare = CGRectApplyAffineTransform(rect, rectTransform);
// use the rect to crop the image
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, transformedCropSquare);
// create a new UIImage and set the scale and orientation appropriately
UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
// memory cleanup
CGImageRelease(imageRef);
return result;
}
在iOS开发中,使用CGImageCreateWithImageInRect进行图片裁剪时,可能会遇到实际裁剪结果与预期相反的情况。原因在于,此方法中的rect基于UIImage坐标系,其原点在左下角,不同于UIImageView。解决办法是将裁剪区域转换到正确坐标系。参考链接提供了解决方案。
1万+

被折叠的 条评论
为什么被折叠?



