Scaling any image to fit UIImageView
Asked Answered
T

2

7

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

Tasiatasiana answered 18/7, 2014 at 20:23 Comment(2)
Set clipToBounds (or Clip Subviews from storyboard) to YES for your UIImageView.Elephus
why did I receive a downvote...Tasiatasiana
D
8

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

Doriandoric answered 18/7, 2014 at 20:46 Comment(0)
F
5

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

Forwardlooking answered 25/5, 2015 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.