Is it possible to resize a UIImage without losing

2019-07-13 12:25发布

I have a UIImage that I put in a UIImageView which has a pinch gesture recognizer attached to it which I use to scale the image. When I scale the image in the UIImageView, there is no distortion and it scales perfectly. However, I need to resize the UIImage while not in the UIImageView, and when I do this using the following code, the result is slightly skewed:

CGFloat width = self.imageView.frame.size.width;
CGFloat height = self.imageView.frame.size.height;

UIGraphicsBeginImageContext(CGSizeMake(width, height));
[self.image drawInRect:CGRectMake(0, 0, width, height)];
UIImage *resizedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];    
UIGraphicsEndImageContext();

As you can see I'm taking the height and width from the imageView, because that is what the image needs to be scaled to.

I know that it has to be possible to scale it perfectly if the imageView is able to do this, does anyone happen to know what I'm doing incorrectly?

UPDATE: I attached a before / after of an image (which has been rescaled by the user in an imageview) and how it looks after I resized it using the above method.BeforeAfter

2条回答
仙女界的扛把子
2楼-- · 2019-07-13 13:06

I had this same issue, I used the following code to help fix it:

    CGFloat scale = 1.0;
if([[UIScreen mainScreen]respondsToSelector:@selector(scale)]) {        
    CGFloat tmp = [[UIScreen mainScreen]scale];
    if (tmp > 1.5) {
        scale = 2.0;    
    }
} 

if(scale > 1.5) {
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, scale);
} else {
    UIGraphicsBeginImageContext(targetSize);
}
查看更多
我命由我不由天
3楼-- · 2019-07-13 13:29

Try this:

+ (UIImage*)rescaleImage:(UIImage *)image scaledToSize:(CGRect)newSize {
    UIGraphicsBeginImageContext(newSize.size);
    [image drawInRect:newSize];
    UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImage;
}
查看更多
登录 后发表回答