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

}

猜你喜欢

转载自blog.csdn.net/openglnewbee/article/details/80396977