How to make fit a larger image into the small image view

1.3k views Asked by At

I have the image view which has fixed size. But I want to fit every size of image into this without stretching.

I tried this

In method resizeImage, I passed my selected image and size of UIImageView.

 func resizeImage(image: UIImage, size: CGSize) -> UIImage {

        UIGraphicsBeginImageContext(size)
        image.drawInRect(CGRectMake(0, 0, size.width, size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

But this is not working, It is still returning the stretched image.

Please let me know what could be the proper solution.

Thanks

2

There are 2 answers

6
konrad.bajtyngier On

I think what you are looking for is your UIImageView's contentMode property. Like so:

myImageView.contentMode = .ScaleAspectFit

This value will make sure that when you set the view's image, the image will fill the view as much as possible without stretching the image. You could also use .ScaleAspectFill to completely fill the view, but then your image will be cropped.

4
TotoroTotoro On

Just do this:

imageView.contentMode = .ScaleAspectFill

When you do this, two things happen:

  1. the image in the image view keeps the correct aspect ratio (i.e. it's not stretched),
  2. The image fills the image view completely. If needed, the center part of the image is cropped. E.g. if your image view is square, and the image is a rectangle, then the image will be cropped to a square.