Image is not fit to the frame of UIImageView

38,613

Solution 1

Either use

imageView.contentMode = UIViewContentModeScaleAspectFill;

or

imageView.contentMode = UIViewContentModeScaleAspectFit;

The first one will fill the frame, possibly cutting off parts of your image. The second one will show the entire image, possibly leaving areas of the frame open.

Solution 2

For Swift :

imageView.contentMode = UIViewContentMode.ScaleAspectFit

For Objective-C :

 imageView.contentMode = UIViewContentModeScaleAspectFit

ScaleAspectFit option is use to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining areas of the view’s bounds is transparent.

Screenshot

Refer Apple docs for details.

Solution 3

I ended up resizing the image after the image was scaled according to it's aspect ratio.

let widthRatio = ImageView.bounds.size.width / (captureImageView.image?.size.width)!
let heightRatio = ImageView.bounds.size.height / (captureImageView.image?.size.height)!
let scale = min(widthRatio, heightRatio)
let imageWidth = scale * (ImageView.image?.size.width)!
let imageHeight = scale * (ImageView.image?.size.height)!
ImageView.frame = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
Share:
38,613
Venk
Author by

Venk

.....

Updated on November 13, 2020

Comments

  • Venk
    Venk over 3 years

    I am creating the UIImageView using interface Builder. Its frame size is (320,67). I want to display the image on the imageView. I am getting the image from the web. The problem is that the image get from web is stretched to display on the imageview... Here my code

    NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.isco.com/webproductimages/appBnr/bnr1.jpg"]];
    imageView.image = [UIImage imageWithData:imageData];
    

    Can anyone tel me that how to display the image fit to display on imageView????