I wanted to resize a UIImage to a certain width and height keeping the proportion in place. The simplest way to do this is:
CGSize newSize = CGSizeMake(726, 521);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Does the method above have any drawbacks in terms of image quality and the time it takes? What is a better way than the method above?
EDITED:
How about this one:
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// this is actually the interesting part:
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil) NSLog(@"could not scale image");
return newImage ;
}
Compute the scaling factor for the vertical dimension to get the desired height, then compute the result of this scaling applied to the horizontal dimension. This may not match the target width, so compute the aspect ratio to apply to the scaled width to correct it to the desired target width.
Assuming that you are referring to the layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
In a performance sample of Image Resizing Techniques the score was
so the fastest and simplest way is:
let renderer = UIGraphicsImageRenderer(size: size)
let resized = renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: size))
}
Resize a UIImage the right way is from 2009 but contains useful talk about interpolation quality and preserving the aspect ratio.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With