Eleonora Ciceri
Eleonora Ciceri

Reputation: 1798

Fit UIImageView to image content

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

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.

Upvotes: 1

Views: 6843

Answers (3)

mdewitt
mdewitt

Reputation: 772

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>

Upvotes: 5

Mathew
Mathew

Reputation: 1798

"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.

Upvotes: 0

Sonny Saluja
Sonny Saluja

Reputation: 7287

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

Upvotes: 1

Related Questions