Is it possible to scale composable content, to fit...
# compose
p
Is it possible to scale composable content, to fit the available space, while keeping aspect ratio? I would like to scale down my composable, to avoid being cut off, it there is no space. Similar to how
ContentScale.Fit
works for
Image()
.
t
I do not have a ready solution but i think this could be possible technically. There is this Modifier.graphicsLayer which you can use for scaling. Maybe you need to encapsulate your composable in a Modifier.wrapContent and then measuer the size Modifier.onSizeChanged and depending on that you can change the scale of the graphicsLayer.
a
Instead of using
Modifier.onSizeChanged
which needs two layout passes, you can just use a layout modifier:
Copy code
Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(Constraints())
    val scale = min(
        constraints.maxWidth / placeable.width.toFloat(),
        constraints.maxHeight / placeable.height.toFloat()
    ).coerceAtMost(1f)
    val size = constraints.constrain(
        IntSize(
            (placeable.width * scale).roundToInt(),
            (placeable.height * scale).roundToInt()
        )
    )
    layout(size.width, size.height) {
        placeable.placeWithLayer(
            x = (size.width - placeable.width) / 2,
            y = (size.height - placeable.height) / 2
        ) {
            scaleX = scale
            scaleY = scale
        }
    }
}
👍 1
🍺 1
t
Yes this is the way to go. Much better than my recommendation
p
Thanks Albert!
👍 1
t
This is why i love compose ❤️. It is possible to find so simple and elegant solutions for complex problems 😄