简体   繁体   中英

UIImageView doesn't resize itself to the UIImage it holds

I have a UIImageView with Auto-layout to the container margins. I set a UIImage to it in the ViewController. 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. 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.

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. 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. I'd suggest doing it in layoutSubviews or updateConstraints method of your view or in view controller's viewDidLayoutSubviews .

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