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?


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.


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

imageView.clipsToBounds = YES;
imageView.contentMode = UIViewContentModeScaleAspectFit;

Use the contentMode property. You probably want either UIViewContentModeScaleAspectFit or UIViewContentModeCenter.


Change the UIImage's Mode from 'scale to fill' to 'Center' within the interface builder. Make sure your image is the exact size you need.

enter image description here