Reputation: 14527
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.
Upvotes: 2
Views: 1854
Reputation: 21
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);
}
Upvotes: 1
Reputation: 8720
Try this:
+ (UIImage*)rescaleImage:(UIImage *)image scaledToSize:(CGRect)newSize {
UIGraphicsBeginImageContext(newSize.size);
[image drawInRect:newSize];
UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resImage;
}
Upvotes: 1