Apollo
Apollo

Reputation: 9054

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

Upvotes: 7

Views: 11993

Answers (2)

Karoly Nyisztor
Karoly Nyisztor

Reputation: 3595

Actually UIViewContentModeScaleAspectFill will also work if you enable clipping as arturdev suggested. Set clipToBounds to YES (or enable "Clip Subviews" in storyboard). This will cause your image to stretch over the entire view, and the excess gets cut out. In some cases this is the preferred behaviour over UIViewContentModeScaleAspectFit; the latter will leave empty spaces if the image does not perfectly fit the view rectangle. enter image description here

Upvotes: 5

matt
matt

Reputation: 534914

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).

Upvotes: 8

Related Questions