Reputation: 3435
I have UIImageView
of a random size, and I want the image to be bottom-aligned and width-scaled preserving the aspect ratio.
Blue rect is UIImageView
, and filled green rect is the image. When aspect ratio (i.e. width/height) of the view is small, image occupies the bottom part of the view (left hand side image). When aspect ratio of the view is large, image gets clipped (right hand side image). Image is scaled to fill the width of the view in both cases.
How do I implement this behavior? I guess I should use
imageView.contentMode = .scaleAspectFill
which preserves aspect ratio, but how do I make the image sticked to the bottom of the view?
Upvotes: 0
Views: 80
Reputation: 671
If you are using Storyboards, use the constraints to setup the image to attach to the right places with the relevant margin.
If you are doing so programmatically, you can use anchors:
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
imageView.leftAnchor...
And if you are not using auto-layer, just position the image to the bottom of the view using frame:
imageView.frame = CGRect(
x: (UIScreen.main.bounds.size.width - imageView.frame.size.width) / 2,
y: UIScreen.main.bounds.size.height - imageView.frame.size.height,
width: imageView.frame.size.width,
height: imageView.frame.size.height)
Upvotes: 0