Swift UIImageView Stretched Aspect

I added an autoresizing mask to the UIImageView and it now displays the correct ratios.

imageView.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth
imageView.contentMode = UIViewContentMode.ScaleAspectFit

This answer helped me: Captured photo is stretched with AVCaptureSession sessionPreset = AVCaptureSessionPresetPhoto as I was using an image that was taken through the phones camera.


Swift 3 version of your code:

imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
imageView.contentMode = .scaleAspectFit // OR .scaleAspectFill
imageView.clipsToBounds = true

That's the intended behaviour for UIViewContentMode.ScaleAspectFit. From the docs:

UIViewContentModeScaleAspectFit

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

It seems from what you describe that you need UIViewContentMode.ScaleAspectFill

UIViewContentModeScaleAspectFill

The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.


I was having the same issue, and what fixed it for me was making sure to set the imageView image after the content mode was set. ie:

    self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
    self.imageView.image = imageChosen

Cheers