-1

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

Gopal Devra
  • 564
  • 2
  • 5
  • 24

2 Answers2

1

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.

Hugo Alonso
  • 6,684
  • 2
  • 34
  • 65
konrad.bajtyngier
  • 1,786
  • 12
  • 13
1

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.
TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
  • Thanks Macondo2Seattle But I want to show the selected image without cropped area Without any stretching. ScaleAspectFill crop the image. – Gopal Devra Feb 15 '16 at 16:10
  • 1
    @GopalDevra what you are trying to do is like trying to fit a soccer ball inside of a square box. You will end up losing the rounded shape of your ball. It just doesn't fit. – Hugo Alonso Feb 15 '16 at 16:17
  • @GopalDevra in that case @konrad.bajtyngier has the right answer. Using `.ScaleAspectFit` ensures that the image is not stretched, and is fully visible inside your image view. – TotoroTotoro Feb 15 '16 at 16:55
  • @GopalDevra another option for you is to ensure that your images and image views all have the same aspect ratio. Then you can show your images without any stretch or cropping, and with no empty space around them. – TotoroTotoro Feb 15 '16 at 16:57