[英]Make UIImageView fit width of screen but keep aspect ratio [swift]
[英]How to display a UIImageView that fills the width of the screen, and sets height to keep aspect ratio?
我有一个这样初始化的图像视图:
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
[self.imageView setContentMode:UIViewContentModeScaleAspectFill];
self.imageView.clipsToBounds = YES;
然后,我在网络上获取图像并将其放置在视图中。 我的问题是我实际上想要显示完整图像,而不是对其进行裁剪,因此适合200 px。
我该怎么做? 谢谢!
因此,您检查图像并根据图像的尺寸计算宽度:
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);
与使用宏( CGRectGetWidth(self.view.bounds)
)相比,有一种更好的获取屏幕宽度的方法,但这与您的问题无关。
使用内容模式UIViewContentModeScaleAspectFit
缩放图像以适合图像视图,同时保持图像的长宽比。
您的问题标题与您的问题正文不匹配,因此我将继续讨论:
我的问题是我实际上想要显示完整图像,而不是对其进行裁剪,因此适合200 px。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.