aspectRatio

Functions summary

Modifier
Modifier.aspectRatio(
    ratio: @FloatRange(from = 0.0, fromInclusive = false) Float,
    matchHeightConstraintsFirst: Boolean
)

Attempts to size the content to match a specified aspect ratio by trying to match one of the incoming constraints in the following order: Constraints.maxWidth, Constraints.maxHeight, Constraints.minWidth, Constraints.minHeight if matchHeightConstraintsFirst is false (which is the default), or Constraints.maxHeight, Constraints.maxWidth, Constraints.minHeight, Constraints.minWidth if matchHeightConstraintsFirst is true.

Cmn

Functions

Modifier.aspectRatio

fun Modifier.aspectRatio(
    ratio: @FloatRange(from = 0.0, fromInclusive = false) Float,
    matchHeightConstraintsFirst: Boolean = false
): Modifier

Attempts to size the content to match a specified aspect ratio by trying to match one of the incoming constraints in the following order: Constraints.maxWidth, Constraints.maxHeight, Constraints.minWidth, Constraints.minHeight if matchHeightConstraintsFirst is false (which is the default), or Constraints.maxHeight, Constraints.maxWidth, Constraints.minHeight, Constraints.minWidth if matchHeightConstraintsFirst is true. The size in the other dimension is determined by the aspect ratio. The combinations will be tried in this order until one non-empty is found to satisfy the constraints. If no valid size is obtained this way, it means that there is no non-empty size satisfying both the constraints and the aspect ratio, so the constraints will not be respected and the content will be sized such that the Constraints.maxWidth or Constraints.maxHeight is matched (depending on matchHeightConstraintsFirst).

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.width(100.dp).aspectRatio(2f).background(Color.Green))
Parameters
ratio: @FloatRange(from = 0.0, fromInclusive = false) Float

the desired width/height positive ratio

matchHeightConstraintsFirst: Boolean = false

if true, height constraints will be matched before width constraints and used to calculate the resulting size according to ratio