Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIImageView Stretched Aspect

UIImageView renders the size of an image incorrectly. Using Scale Aspect Fit, if the UIImageView is a square the image is the correct aspect ratio with transparency in the areas the image does not fill.

//Image is Square & Correct Size var imageView = UIImageView(frame: CGRectMake(0, 50, 320, 320)) imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.ScaleAspectFit  //Image is Rectangle & Incorrect Size var imageView = UIImageView(frame: CGRectMake(0, 50, 320, 450)) imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.ScaleAspectFit 

The UIImageView needs to touch the edges and have transparent space at the top and bottom of the screen and the image inside needs to keep its original ratio rather than stretching taller. I have attached two images of how the image inside the UIImageView is rendering.

ImageView with correct AspectImageView with wrong Aspect

like image 774
George Grover Avatar asked Jan 15 '15 10:01

George Grover


1 Answers

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.

like image 115
George Grover Avatar answered Sep 25 '22 21:09

George Grover