UIImage: Resize, then Crop

后端 未结 16 2548
夕颜
夕颜 2020-11-22 11:51

I\'ve been bashing my face into this one for literally days now and even though I feel constantly that I am right on the edge of revelation, I simply cannot achieve my goal.

16条回答
  •  星月不相逢
    2020-11-22 12:30

    Here you go. This one is perfect ;-)

    EDIT: see below comment - "Does not work with certain images, fails with: CGContextSetInterpolationQuality: invalid context 0x0 error"

    // Resizes the image according to the given content mode, taking into account the image's orientation
    - (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode imageToScale:(UIImage*)imageToScale bounds:(CGSize)bounds interpolationQuality:(CGInterpolationQuality)quality {
        //Get the size we want to scale it to
        CGFloat horizontalRatio = bounds.width / imageToScale.size.width;
        CGFloat verticalRatio = bounds.height / imageToScale.size.height;
        CGFloat ratio;
    
        switch (contentMode) {
            case UIViewContentModeScaleAspectFill:
                ratio = MAX(horizontalRatio, verticalRatio);
                break;
    
            case UIViewContentModeScaleAspectFit:
                ratio = MIN(horizontalRatio, verticalRatio);
                break;
    
            default:
                [NSException raise:NSInvalidArgumentException format:@"Unsupported content mode: %d", contentMode];
        }
    
        //...and here it is
        CGSize newSize = CGSizeMake(imageToScale.size.width * ratio, imageToScale.size.height * ratio);
    
    
        //start scaling it
        CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
        CGImageRef imageRef = imageToScale.CGImage;
        CGContextRef bitmap = CGBitmapContextCreate(NULL,
                                                    newRect.size.width,
                                                    newRect.size.height,
                                                    CGImageGetBitsPerComponent(imageRef),
                                                    0,
                                                    CGImageGetColorSpace(imageRef),
                                                    CGImageGetBitmapInfo(imageRef));
    
        CGContextSetInterpolationQuality(bitmap, quality);
    
        // Draw into the context; this scales the image
        CGContextDrawImage(bitmap, newRect, imageRef);
    
        // Get the resized image from the context and a UIImage
        CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
        UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
        // Clean up
        CGContextRelease(bitmap);
        CGImageRelease(newImageRef);
    
        return newImage;
    }
    

提交回复
热议问题