wrapContentWidth

Compose Modifier

Common
fun Modifier.wrapContentWidth(
    align: Alignment.Horizontal = Alignment.CenterHorizontally,
    unbounded: Boolean = false,
) =
    this.then(
        if (align == Alignment.CenterHorizontally && !unbounded) {
            WrapContentWidthCenter
        } else if (align == Alignment.Start && !unbounded) {
            WrapContentWidthStart
        } else {
            WrapContentElement.width(align, unbounded)
        }
    )

Allow the content to measure at its desired width without regard for the incoming measurement minimum width constraint, and, if unbounded is true, also without regard for the incoming measurement maximum width constraint. If the content's measured size is smaller than the minimum width constraint, align it within that minimum width space. If the content's measured size is larger than the maximum width constraint (only possible when unbounded is true), align over the maximum width space.

Code Examples

SimpleWrapContentHorizontallyAlignedModifier

@Composable
fun SimpleWrapContentHorizontallyAlignedModifier() {
    // Here the result will be a 20.dp x 50.dp blue box centered vertically in a 50.dp x 50.dp
    // space. Because of the size modifier, if wrapContentWidth did not exist,
    // the blue rectangle would actually be 50.dp x 50.dp to satisfy the size set by the modifier.
    // However, because we provide wrapContentWidth, the blue rectangle is specified to be wrap
    // content in width - if the desired width is smaller than 50.dp, it will be centered
    // horizontally in this space. Therefore the 50.dp x 20.dp is centered horizontally
    // in the space.
    Box(
        Modifier.size(50.dp)
            .wrapContentWidth(Alignment.CenterHorizontally)
            .width(20.dp)
            .background(Color.Blue)
    )
}