R3ptor R3ptor - 1 month ago 11
Swift Question

Change size of UIImageView to fit different UIImages

So I have my UIImageView which is called

imgView
. 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
imgView
should change it's size everytime to perfectly fit the image with aspectFit. If the image is small the
imgView
shrinks so it doesn't take up much space etc.

I have used this code in my
viewDidLoad
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


or

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


What should I do differently?

Answer

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)
        view.layoutIfNeeded()
    }

}

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