简体   繁体   中英

Fit UIImageView to image content

Is it possible to fit perfectly an UIImageView to its content, so that:

  • the origins of the image and the UIImageView object coincide;
  • the frame of the image and the UIImageView object coincide?

I tried using the following code:

self.imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.imageView setBounds:CGRectMake(self.imageView.bounds.origin.x,
                                     self.imageView.bounds.origin.y,
                                     self.imageView.bounds.origin.x + self.imageView.image.size.width,
                                     self.imageView.bounds.origin.y + self.imageView.image.size.height)];

However, in this way the UIImageView object starts at (0,0) , while the image is centered on the screen.

Thanks in advance.

I think what you're looking for is something along the lines of:

   [self.imageView setFrame: AVMakeRectWithAspectRatioInsideRect(imageSize, self.imageView.frame)];

Where imageSize is the aspect ratio you wish to maintain, and the in this case self.imageView.frame is the bounding rect.

This is part of the AVFoundation Framework so make sure to include:

  #import <AVFoundation/AVFoundation.h>

From your description, it seem you want UIViewContentModeScaleAspectFill.

UIViewContentModeScaleAspectFit - will fit the image inside the image view. If the image is smaller than the image view it will be centered.

UIViewContentModeScaleAspectFill - will fill the image inside the image view. If the image is smaller/bigger than the image view it will be scaled.

Apple Documentation for UIViewContentMode

"Is it possible to fit perfectly an UIImageView to its content?" Yes. Your code attempts to set the bounds of the UIImageView . What it sounds like you want to do, is set the frame of the UIImageView to the size of the image.

Do a bit of Googling if you are unfamiliar with the difference between the frame of a UIView and the bounds of a UIView ; it is an important distinction. If you want to set the actual size or location of the UIImageView , use its frame , which operates in the coordinate space of the UIView that contains your UIImageView . If instead you wanted to affect the coordinate space of views contained by your UIImageView , you would use the bounds .

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