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

Posted openglnewbee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在UIImage中按坐标截出新的UIImage的完美代码(网上绝大部分都有问题!)相关的知识,希望对你有一定的参考价值。

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

以上是关于在UIImage中按坐标截出新的UIImage的完美代码(网上绝大部分都有问题!)的主要内容,如果未能解决你的问题,请参考以下文章

在 UIScrollView 中获取 UIImage 可见部分的正确坐标

iOS - 根据坐标更改 UIImage 的方向

从IOS中的UIImage获取坐标和框架

OS: 剪裁UIImage部分不规则区域

将 SwiftUI 视图渲染到屏幕外并将视图另存为 UIImage 以共享

delphi xe 移动开发 调用截屏