图片一边裁剪掉一块区域,精确到像素

  1. 计算裁剪后的矩形区域,即CGRect的origin.x为0,origin.y为0,宽度为原宽度减去要裁剪的右边部分,高度不变。
  2. 创建基于位图的图形上下文,并设置适当的大小。
  3. 在上下文中绘制原始图片的指定区域。
  4. 从上下文中生成新的UIImage。
  5. 释放图形上下文资源。

需要注意的点:

  • 处理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];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值