简体   繁体   中英

UIImageView with fixed width: how to set its height to keep its aspect?

I have a view where I need to place an UIImageView , and I was told to place it inside a rectangle that takes the screen width and its height is smaller than width (fixed size). However, the images I've been given are more or less square jpeg images, so the idea is to fill the width of the rectangle that should contain the image and set the height of the image in a way that its aspect ratio is kept. Then, I should be able to let the user scroll the image vertically to see the complete image.

How could I do this?

Thanks in advance

EDIT: I need to do this for several images that have different sizes, but that should fit the same rectangular area size within the view

You can set imageview content mode.

imageView.contentMode = UIViewContentModeScaleAspectFit;

This will make sure that the image is displayed by keeping original aspect ratio.

Edit:

I think this is what you wanted:

UIImage *originalImage = [UIImage imageNamed:[picArr objectAtIndex:a]];
double width = originalImage.size.width;
double height = originalImage.size.height;
double apect = width/height;

double nHeight = 320.f/ apect;
self.img.frame = CGRectMake(0, 0, 320, nHeight);
self.img.center = self.view.center;
self.img.image = originalImage;

Hope this helps.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM