Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling any image to fit UIImageView

I'm a little but confused as to how I could make an image taken by an iPhone camera to fit into a UIImageView of any given size. Obviously the scale would be different for each imageview so the image wouldn't "fit" perfectly. But let's say I have a UIImageView of size 200pt x 400 pt. What would be the best way to fit a UIImage to this UIImageView?

I think I want to do something like the following:

[imageView setContentMode:UIViewContentModeScaleAspectFill];

This sort of works, but it seems to increase the size of my UIImageView but I don't want this...

enter image description here

like image 259
Apollo Avatar asked Jul 18 '14 20:07

Apollo


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do you adjust the way an image is fitted to its space Swift?

To make an image scales to fit the current view, we use the resizable() modifier, which resizes an image to fit available space. We can see the whole image now, but it got stretched out and losing its aspect ratio, which is usually not the behavior we want. The image view resize to fit available space.


1 Answers

Use setContentMode:UIViewContentModeScaleAspectFit (not Fill; Fill means that one dimension is permitted to be too large for the image view, and you will be able to see the excess spill over if the image view's clipsToBounds is not set).

Also, note that setting the image of an existing UIImageView when using auto layout can cause the image view's size to change (because the size of the image determines the intrinsic size of the image view). If you don't want that, add constraints to maintain the height and width at some constant value (e.g. explicit height and width constraints).

like image 66
matt Avatar answered Sep 28 '22 15:09

matt