Reputation: 3356
I am creating an iOS app where I have images larger then my UIImageView. I want to scale these images so the image height is the same as the image view height. Instead of the images getting clipped on 2 sides it will only get clipped on one. How do I scale the UIImages? UIViewContentModeScaleAspectFit fits the longest end so the entire image is on the screen but I want it to fit the height not the longest end.
Upvotes: 0
Views: 3407
Reputation: 705
Try this code,
//find out the width and height ratio of your image.
double ratio = [UIImage imageNamed:@"Your_image.png"].size.width / [UIImage imageNamed:@"Your_image.png"].size.height;
//determine the calculate width according the height. here height is set as 568.
double calculatedWidth = ratio * 568;
float xPosition = 0.0;
//if calculated width is greater than the screen width than we need to change the starting position which was set to 0 initially.
if (calculatedWidth > [UIScreen mainScreen].bounds.size.width)
{
xPosition = (calculatedWidth - [UIScreen mainScreen].bounds.size.width) * - 1;
}
//initiate your image view here.
UIImageView *yourImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xPosition, 0, calculatedWidth, 568)];
yourImageView.image = [UIImage imageNamed:@"Your_image.png"];
[self.view addSubview:yourImageView];
Upvotes: 2
Reputation: 53860
Here's how you get what you want:
// Set image view to clip to bounds
self.imageView.clipToBounds = YES;
// Calculate aspect ratio of image
CGFloat ar1 = self.imageView.image.size.width / self.imageView.image.size.height;
// Calculate aspect ratio of image view
CGFloat ar2 = self.imageView.frame.size.width / self.imageView.frame.size.height;
// Set fill mode accordingly
if (ar1 > ar2) {
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
} else {
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
}
Upvotes: 1
Reputation: 4373
If you want to make only the height exactly fit within the image view, you need to do a little math to find out the proper width ratio. Try this:
float maxHeight = 480.0f; //this is the height of your container view.
float origHeight = imageView.frame.size.height;
float origWidth = imageView.frame.size.width;
//at this point we can create a proportion.
//origHeight / origWidth = maxHeight / X (where X = the new width)
//divide the expression by maxHeight and you can solve for the new width:
float newWidth = (origHeight / origWidth) / maxHeight;
At this point you have the size that you need to make the image; you always want the height to be whatever maxHeight is, and you've done math to find out the new width that is proportional to the original image size when height = maxHeight.
Check out this answer here on StackOverflow on how to resize UIImageViews. Pass that height and width to the function in that answer. And all should be well!
Upvotes: 1