R3ptor R3ptor - 7 months ago 97
Swift Question

Change size of UIImageView to fit different UIImages

So I have my UIImageView which is called

. Basically the user can add his own images to this view and save it again to his own gallery.

Because I don't know beforehand what the sizes the images from the User are the
should change it's size everytime to perfectly fit the image with aspectFit. If the image is small the
shrinks so it doesn't take up much space etc.

I have used this code in my
to achieve it but it doesn't do anything:

imgView.frame.size.width = imgView.image?.size.width
imgView.frame.size.height = imgView.image?.size.height


imgView.bounds.size = imgView.image?.size

What should I do differently?


Update width & height constraints:

I assume you're using autolayout. If so, you should change constraints' constant values instead of setting frames manually. Here is an example:

class ImageViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!    
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!

    func setImage(image: UIImage) {
        imageView.image = image
        widthConstraint.constant = min(image.size.width, view.bounds.size.width)
        heightConstraint.constant = min(image.size.height, view.bounds.size.height)


Note, that you also have to drag outlets for width and height constraints from storyboard to your viewController

Another solution without resizing UIImageView:

If other UI elements don't rely on UIImageView's frame and the only thing you care about is image appearance, you can just set content mode to Center or Top/Bottom/Right/Left etc:

enter image description here

Just set UIImageView's background to clear color