简体   繁体   English

如何显示一个UIImageView来填充屏幕的宽度,并设置高度以保持纵横比?

[英]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.

相关问题 使UIImageView适合屏幕宽度,但保持宽高比[swift] - Make UIImageView fit width of screen but keep aspect ratio [swift] UIImageView 保持纵横比,但适合宽度 - UIImageView keep aspect ratio, but fit to width 具有固定宽度的UIImageView:如何设置其高度以保持其宽高? - UIImageView with fixed width: how to set its height to keep its aspect? 使图像适合屏幕顶部,填充宽度,保持宽高比 - Fit image to top of screen, fill width, keep aspect ratio 使自定义TableViewCell的UIimageView宽度为单元格宽度的1/3,并且单元格的高度=图像宽高比 - Have UIimageView width of custom TableViewCell be 1/3 of cell width, and height of cell = image aspect ratio 在自定义UITableViewCell中保持UIImageView的长宽比 - Keep aspect ratio of an UIImageView in a custom UITableViewCell 如何缩放填充整个屏幕的UIImageView - How to Zoom a UIImageView that fills the screen 如何找到图像的高度和宽度并使tableviewcell具有高宽比? - How to find the height and width of image and fit the tableviewcell with aspect ratio? 受宽度和纵横比限制的视图,不更新高度 - Views constrained by width and aspect ratio, not updating height 如何隐藏具有纵横比自动布局约束的UIImageView? - How to hide an UIImageView with Aspect Ratio autolayout constraint?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM