Search code examples
iosswiftuiimageviewnslayoutconstraint

what is wrong with constraints in my UIImageView and why I cannot stretch the image on my UIViewController?


This is my current situation:

enter image description here

I have a UIViewController with UIImageView on it.

The latter has the following constraints: trailing to superview, leading to superview, top space to top layout guide, width equals 320, height equals 820.

Height and width are connected as outlets to my class and I'm setting them in viewDidLoad:

@IBOutlet weak var imageHeightconstraint: NSLayoutConstraint!

@IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!

@IBOutlet weak var backgroundImage: UIImageView!

override viewDidLoad(){
    backgroundImage.af_setImageWithURL(NSURL(string: photoURL)!)
    imageHeightconstraint.constant = backgroundImage.image!.size.height
    imageWidthConstraint.constant = self.view.frame.size.width
}

Now, my image is this:

enter image description here

it is 480x640px photo. I tried in my storyboard to set the mode to center, scale to fill, aspect fill, aspect fit and top.

For example, this is center:

enter image description here

aspect fit:

enter image description here

aspect fill:

enter image description here

but I don't know how to stretch this image from left to right and keep the aspect ratio, so the whole photo is visible and its left and right edges stick to the left and right edge of the screen. I thought those two constraints could fix it:

imageHeightconstraint.constant = backgroundImage.image!.size.height
imageWidthConstraint.constant = self.view.frame.size.width

but it does not work. Maybe the problem is that the resolution of the photo is low (480x640), so the height is only that small? Can you give me any hint how could I fix it?


Solution

  • To have the image stick to both sides of screen and maintain the aspect ratio, set these 4 constraints:

    1. Leading Edge of ImageView to Leading Edge of SuperView.
    2. Trailing Edge of ImageView to Trailing Edge of SuperView.
    3. Top Edge of ImageView to Top Layout Guide Bottom.
    4. Set an aspect ratio constraint: ImageView Width equal to ImageView Height with multiplier 480:640. To set this, control-drag diagonally in the ImageView and select Aspect Ratio from the pop-up. Then change the multiplier to 480:640.

      aspect ratio constraint

    Set the content mode for the image to Scale to fill.