Member-only story
How to Set the Aspect Ratio for a View in XML Using ‘constraintDimensionRatio’
Display your images exactly as they were intended to be seen

This post is regarding an important and useful attribute of ConstraintLayout
known as constraintDimensionRatio
. Before exploring this, we should know about aspect ratios and ConstraintLayout
.
Aspect ratio is the term used to describe the dimensions of a view by comparing the width to the height and expressing it in ratio form. The aspect ratio is a measured according to width:height. If the aspect ratio is 4:3, the width should be 4, whereas the height should be 3. This ratio sets the image accordingly.
In Android development, before ConstraintLayout
, we used to use the aspect-ratio formula, fixing either the width or height to get a perfect view of an image. After the introduction of ConstraintLayout
, many things became easy to work within XML.
To know more about ConstraintLayout
, check out “Essential Components of ConstraintLayout.” The ratio is one of the features of ConstraintLayout
that helps to reduce a little of the overhead of setting the aspect ratio programmatically.
Let’s Understand It Better With an Example
When using the constraintDimensionRatio
attribute, we need to have at least one constrained dimension set to 0dp
(e.g., MATCH_CONSTRAINT
), and we need to set the attribute layout_constraintDimensionRatio
to the required ratio. For example, check the below snippet:
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"/>
The above XML will set the height of the button to be the same as the width.
The ratio can be expressed in either of these two ways:
- A float value, representing the ratio between the width and the height
- A ratio in the form “width:height”
We can also use a ratio if both dimensions are set to 0dp
. In this case, the system sets the largest dimensions that satisfy all the constraints mentioned while maintaining the given aspect ratio.