简体   繁体   English

UIImageView 不会将自身调整为它所持有的 UIImage

[英]UIImageView doesn't resize itself to the UIImage it holds

I have a UIImageView with Auto-layout to the container margins.我有一个带有自动布局到容器边距的UIImageView I set a UIImage to it in the ViewController.我在 ViewController 中为它设置了一个UIImage If I use UIViewContentModeScaleAspectFit then the image is centred in the middle of the screen as I wanted and everything looks great, but when I give the UIImageView a background color, I can see it still spreads all the way to the container margins, and doesn't get the image's proportions and dimensions.如果我使用UIViewContentModeScaleAspectFit那么图像会根据我的需要在屏幕中间居中,一切看起来都很棒,但是当我给UIImageView一个背景颜色时,我可以看到它仍然一直蔓延到容器边缘,并且没有t 获取图像的比例和尺寸。 This is my code:这是我的代码:

UIImage *passedImage = [UIImage imageNamed:self.photoTitle];
CGRect imageBounds = CGRectMake(0, 0, passedImage.size.width, passedImage.size.height);
[self.imageView setImage:passedImage];
self.imageView.bounds = imageBounds;
self.imageView.contentMode = UIViewContentModeScaleAspectFit;

I have tried everything to fix it and looked everywhere for answers, please help me, you are my only hope.我已经尝试了一切来修复它并到处寻找答案,请帮助我,你是我唯一的希望。

Instead of pinning the image view's edges to the container margins, pin its center X and center Y to the container's center X and center Y.不要将图像视图的边缘固定到容器边缘,而是将其中心 X 和中心 Y 固定到容器的中心 X 和中心 Y。

This gives the same visual result — the image is centered — but leaves the image view free to resize itself according to its contents.这给出了相同的视觉效果——图像居中——但让图像视图可以根据其内容自由调整自身大小。

UIImageView does not resize itself according to image size it renders. UIImageView 不会根据它呈现的图像大小调整自身大小。 If you need to size it accordingly, you need to do it yourself.如果您需要相应地调整大小,则需要自己进行。 Matt's answer is reasonable, but you still need to update your image view size at some point. Matt 的回答是合理的,但您仍然需要在某个时候更新您的图像视图大小。 I'd suggest doing it in layoutSubviews or updateConstraints method of your view or in view controller's viewDidLayoutSubviews .我建议在视图的layoutSubviewsupdateConstraints方法或视图控制器的viewDidLayoutSubviews

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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