I would like to ask how to scale an image to fill a UIImageView
but still keep its aspect ratio, just like the centerCrop
scale type of Android ImageView
does.
Asked
Active
Viewed 4,242 times
6

Rob
- 415,655
- 72
- 787
- 1,044

Vinh Hung Nguyen
- 139
- 1
- 11
-
https://stackoverflow.com/questions/14134035/how-to-manage-uiimageview-content-mode – Yevgen THD Feb 07 '19 at 06:32
-
Set [`imageView.contentMode`](https://developer.apple.com/documentation/uikit/uiview/1622619-contentmode) to [`.scaleAspectFill`](https://developer.apple.com/documentation/uikit/uiview/contentmode/scaleaspectfill) (or [`.scaleAspectFit`](https://developer.apple.com/documentation/uikit/uiview/contentmode/scaleaspectfit)). – Rob Feb 07 '19 at 06:37
-
@Rob `scaleAspectFit` is equivalent of android `centerInside` – Iffat Fatima Feb 07 '19 at 06:38
-
1@iffatfatima - Yep, I just wanted to share both of the aspect preserving scaling `contentMode`s. – Rob Feb 07 '19 at 06:42
3 Answers
11
You should use .scaleAspectFill
. In swift 4.2:
myImageView.contentMode = .scaleAspectFill
myImageView.clipsToBounds = true // If you want to crop
-
4.scaleAspectFill will stretch the image to fit into UIImageView. If you want to keep the aspect ratio, you should use .scaleAspectFit. The best way is you try both solution in the code to see the final result. If this helps you, please upvote my post. Thank you! – qtngo Feb 07 '19 at 06:57
-
0
You can set image view contentMode
to UIView.ContentMode.scaleAspectFill
. It is equivalent of Android scaleType
centerCrop

Iffat Fatima
- 1,610
- 2
- 16
- 27
0
Following are the main content modes of UIImageView:
- UIViewContentModeScaleToFill
- UIViewContentModeScaleAspectFit
- UIViewContentModeScaleAspectFill
the one to fill the whole imageview is 'ScaleAspectFill' plus you can also use 'clipsToBound' property as true so that it will crop the extra image which is out of imageview.

Zeeshan Ahmed
- 111
- 9
-
1
-
he can write like imageView.contentMode = .scaleAspectFill & if he want to set the image as its pixels quality .scaleAspectFit will be perfect. – Zeeshan Ahmed Feb 07 '19 at 10:12