This is my current situation:
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:
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
:
aspect fit
:
aspect fill
:
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?
To have the image stick to both sides of screen and maintain the aspect ratio, set these 4 constraints:
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
.
Set the content mode for the image to Scale to fill
.