在UIImage中按坐标截出新的UIImage的完美代码(网上绝大部分都有问题!)

本文介绍了一个裁剪并根据原始图像的方向调整裁剪区域的方法。通过使用CGAffineTransform转换,该方法可以处理不同方向的UIImage,并创建一个新的裁剪后的UIImage。文章详细展示了如何根据图像的方向调整裁剪矩形的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

- (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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值