Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop an image from stretching within a UIImageView?

I have a UIImageView where I have set the frame size to x = 0, y = 0, width = 404, height = 712. In my project, I need to change the image in UIImageView dynamically.

I am using this code to change the image:

self.imageView.image = [UIImage imageNamed:@"setting-image.png"]; 

The problem is, when the *.png image size is smaller than the UIImageView frame size, the image stretches. I don't want it to stretch. Is there any way to do that?

like image 909
R. Dewi Avatar asked Aug 12 '11 04:08

R. Dewi


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

Does UIImageView have intrinsic content size?

Here is the essential problem: the only way in which UIImageView interacts with Auto Layout is via its intrinsicContentSize property. That property provides the intrinsic size of the image itself, and nothing more.

How do I change the size of my UIImageView?

Here is a simple way: UIImage * image = [UIImage imageNamed:@"image"]; CGSize sacleSize = CGSizeMake(10, 10); UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, sacleSize.


2 Answers

You can use

self.imageView.contentMode = UIViewContentModeScaleAspectFit; 

Swift 3:

imageView.contentMode = .scaleAspectFit 

Or UIViewContentModeCenter / .center, or any of the other modes described in the UIView documentation.

like image 65
jtbandes Avatar answered Sep 21 '22 13:09

jtbandes


Setting clipsToBounds in combination with UIViewContentModeScaleAspectFit contentMode was what did the trick for me. Hope that helps someone!

imageView.clipsToBounds = YES; imageView.contentMode = UIViewContentModeScaleAspectFit; 
like image 44
Tyler Kidd Avatar answered Sep 21 '22 13:09

Tyler Kidd