Scaling UIImageView to fit screen width

2019-03-27 10:20发布

问题:

I have an UIImageView created using Storyboard inside UIViewController.

I'm trying to rescale the width of the image to fit the screen width and rescale height proportionally:

[fImage setImage:[UIImage imageNamed: @"f2345.jpeg"]];
[fImage sizeToFit];
fImage.contentMode = UIViewContentModeScaleAspectFit;
CGRect frame = filmImage.frame;
frame.size.width = [[UIScreen mainScreen] bounds].size.width;
// Alternative way to do the similar thing - gives the same result in my case
// frame.size.width = [[UIScreen mainScreen] applicationFrame].size.width;
fImage.frame = frame;

It then shows an image which is scaled but it fits some other area and there is a whitespace aruond my image.

回答1:

Try using this code:

float imgFactor = frame.size.height / frame.size.width;
frame.size.width = [[UIScreen mainScreen] bounds].size.width;
frame.size.height = frame.size.width * imgFactor;