- 计算裁剪后的矩形区域,即CGRect的origin.x为0,origin.y为0,宽度为原宽度减去要裁剪的右边部分,高度不变。
- 创建基于位图的图形上下文,并设置适当的大小。
- 在上下文中绘制原始图片的指定区域。
- 从上下文中生成新的UIImage。
- 释放图形上下文资源。
需要注意的点:
- 处理Retina屏幕时,要考虑图片的scale属性,否则可能导致图片模糊。
- 裁剪的宽度不能超过原图宽度,否则会导致异常。
- 需要测试不同的图片方向,确保裁剪正确。
/**
* 精准可控右侧裁剪(像素级控制)
* @param rightTrimWidth 要裁剪的右侧宽度(单位:与image.scale关联的物理像素)
*/
- (UIImage *)preciseRightTrim:(UIImage *)image trimWidth:(CGFloat)rightTrimWidth {
if (!image || rightTrimWidth <= 0) return image;
// 转换参数为像素单位
CGFloat pixelTrim = rightTrimWidth * image.scale;
CGFloat totalPixelWidth = image.size.width * image.scale;
// 动态计算有效裁剪范围
CGFloat validTrim = MIN(pixelTrim, totalPixelWidth - 1);
CGFloat targetPixelWidth = totalPixelWidth - validTrim;
// 核心裁剪逻辑(兼容所有方向)
CGRect cropRect = CGRectMake(0, 0,
targetPixelWidth / image.scale, // 转回点坐标系
image.size.height);
// 坐标系修正(适配UIImageOrientation)
CGAffineTransform transform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
// 其他方向处理...
}
// 创建精准上下文
UIGraphicsBeginImageContextWithOptions(cropRect.size, NO, image.scale);
CGContextConcatCTM(UIGraphicsGetCurrentContext(), transform);
[image drawAtPoint:CGPointMake(-cropRect.origin.x, -cropRect.origin.y)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIImage imageWithCGImage:result.CGImage
scale:image.scale
orientation:image.imageOrientation];
}
方法调用
// 裁剪图片右侧50像素
UIImage *original = [UIImage imageNamed:@"example.jpg"];
UIImage *trimmed = [self trimRightFromImage:original trimWidth:50.0f];