UIImageView is a common component in iOS development for displaying images. One important aspect of UIImageView is the contentMode property, which determines how the image should be scaled and positioned within the bounds of the UIImageView.
There are several options for contentMode, each with its own behavior and use case. As a developer, it's important to understand these options and choose the appropriate contentMode for your specific use case.
In this blog post, we'll go over each contentMode option and provide examples of when to use them. This will serve as a useful reference for developers who frequently work with UIImageView and want to avoid constantly looking up contentMode options.
.scaleAspectFit
The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
.scaleAspectFill
The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.
.scaleToFill
The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary. This option is the default behavior if you don't specify the contentMode for an imageView.
.center
The option to center the content in the view’s bounds, keeping the proportions the same.
.top
The option to center the content aligned at the top in the view’s bounds.
.bottom
The option to center the content aligned at the bottom in the view’s bounds.
.left
The option to align the content on the left of the view.
.right
The option to align the content on the right of the view.
.topLeft
The option to align the content in the top-left corner of the view.
.topRight
The option to align the content in the top-right corner of the view.
.bottomLeft
The option to align the content in the bottom-left corner of the view.
.bottomRight
The option to align the content in the bottom-right corner of the view.
.redraw
The option to redisplay the view when the bounds change by invoking the
setNeedsDisplay()
method.The system won't redraw a view each time the bounds change by default. In cases where we have a custom view that implements the draw(_ rect:) method, and we want it to be called whenever the bounds of the view change, we can use the .redraw content mode. This mode triggers the setNeedsDisplay method, which redraws the view, whenever its bounds are modified.
References