Is it possible to set the contentMode
for my UIImage
to .scaleAspectFit
and .bottom
simultaneously ?
This is how my image looks like at the moment:
UIImageView:
let nightSky: UIImageView = {
let v = UIImageView()
v.image = UIImage(named: "nightSky")
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
Constraints:
nightSky.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
nightSky.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -120).isActive = true
nightSky.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
nightSky.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
Here is a custom class that allows Aspect Fit and Alignment properties.
It is marked
@IBDesignable
so you can see it in Storyboard / Interface Builder.The
@IBInspectable
properties are:Select the image as you would for a normal
UIImageView
.Valid values for
HAlign
are "left" "center" "right" or leave blank for default (center).Valid values for
VAlign
are "top" "center" "bottom" or leave blank for default (center)."Aspect Fill" is
On
orOff
(True/False). If True, the image will be scaled toAspect Fill
instead ofAspect Fit
.Using this image:
Here's how it looks with a 240 x 240
AlignedAspectFitImageView
with background color set to yellow (so we can see the frame):Properties can also be set via code. For example:
To show the difference between "Aspect Fill" and "Aspect Fit"...
Using this image:
We get this result with
Aspect Fill: Off
andVAlign: bottom
:and then this result with
Aspect Fill: On
andHAlign: right
: