Reputation: 27050
I've an UIImage of size (1008, 669) how can I resize it based on my device size (so for e.g. if I'm viewing this in iPhone4s its width will be 640 x 960 ((320 * retina_scale) x (480 * retina_scale)). I'm using below method to do so, but my image just stretched in UIImageView
. How to handle this? How to make it dynamic so that it'll work will all kind of images?
- (UIImage *) hResizeImage:(UIImage *)image withTargetSize:(CGSize)targetSize {
CGSize size = image.size;
CGFloat widthRatio = targetSize.width / image.size.width;
CGFloat heightRatio = targetSize.height / image.size.height;
// Figure out what our orientation is, and use that to form the rectangle
CGSize newSize;
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio);
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio);
}
// This is the rect that we've calculated out and this is what is actually used below
CGRect scaledRect = CGRectMake(0, 0, newSize.width * [UIScreen mainScreen].scale, newSize.height * [UIScreen mainScreen].scale);
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, [UIScreen mainScreen].scale);
[image drawInRect:scaledRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Upvotes: 2
Views: 918
Reputation: 201
Since the scale factor is specified in UIGraphicsBeginImageContextWithOptions, it is not needed to multiply the width and height by the screen scale when scaledRect is calculated.
And If you specify a value of 0.0 in UIGraphicsBeginImageContextWithOptions, the scale factor is automatically set to the scale factor of the device’s main screen.
- (UIImage *)hResizeImage:(UIImage *)image withTargetSize:(CGSize)targetSize {
CGSize size = image.size;
CGFloat widthRatio = targetSize.width / image.size.width;
CGFloat heightRatio = targetSize.height / image.size.height;
// Figure out what our orientation is, and use that to form the rectangle
CGSize newSize;
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio);
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio);
}
// This is the rect that we've calculated out and this is what is actually used below
CGRect scaledRect = CGRectMake(0, 0, newSize.width, newSize.height);
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0f);
[image drawInRect:scaledRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Upvotes: 1