[英]How to display a UIImageView that fills the width of the screen, and sets height to keep aspect ratio?
I have an image view I initialize like this: 我有一个这样初始化的图像视图:
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
[self.imageView setContentMode:UIViewContentModeScaleAspectFill];
self.imageView.clipsToBounds = YES;
I then fetch the image on the web and place it in the view. 然后,我在网络上获取图像并将其放置在视图中。 My problem is that I actually want to show the full image, and not crop it so it fits 200 px.
我的问题是我实际上想要显示完整图像,而不是对其进行裁剪,因此适合200 px。
How I can I do this? 我该怎么做? Thanks!
谢谢!
So you inspect the image and calculate the width based on the image's dimensions: 因此,您检查图像并根据图像的尺寸计算宽度:
UIImage *downloadedImage; // assuming this is not nil
CGFloat imageRatio = downloadedImage.size.height / downloadedImage.size.width;
self.imageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * imageRatio);
There is a better way to get the screen width than using a macro by the way ( CGRectGetWidth(self.view.bounds)
), but that's not relevant to your question. 与使用宏(
CGRectGetWidth(self.view.bounds)
)相比,有一种更好的获取屏幕宽度的方法,但这与您的问题无关。
Using the content mode UIViewContentModeScaleAspectFit
scales the image to fit the image view, keeping the aspect ratio of the image. 使用内容模式
UIViewContentModeScaleAspectFit
缩放图像以适合图像视图,同时保持图像的长宽比。
Your question title doesn't match your question body, so I'm going with the body: 您的问题标题与您的问题正文不匹配,因此我将继续讨论:
My problem is that I actually want to show the full image, and not crop it so it fits 200 px.
我的问题是我实际上想要显示完整图像,而不是对其进行裁剪,因此适合200 px。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.