Is there a better way to achieve this "scale conte...
# compose
r
Is there a better way to achieve this "scale content to fit" effect? I want to lay out a composable, then scale the drawing of any children to fit inside it. Important requirements: (1) I don't know the size of the parent or the children, (2) Child composables should be laid out at their intrinsic size:
Copy code
fun Modifier.scaleContentToFit(): Modifier = composed {
    var frameSize by remember { mutableStateOf<Size?>(null) }
    this
        .graphicsLayer {
            frameSize = size
        }
        .wrapContentSize(unbounded = true)
        .graphicsLayer {
            frameSize?.let { frameSize ->
                // Scale that fits graphicsLayer.size fully inside frameSize
                val scale = min(
                    frameSize.width / size.width,
                    frameSize.height / size.height)
                this.scaleX = scale
                this.scaleY = scale
            }
        }
}
a
You can do that with a single layout modifier:
Copy code
Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(Constraints())
    val (width, height) = constraints.constrain(IntSize(placeable.width, placeable.height))
    layout(width, height) {
        placeable.placeWithLayer(
            x = (width - placeable.width) / 2,
            y = (height - placeable.height) / 2
        ) {
            // Set scaleX and scaleY
        }
    }
}
💯 1
r
Ooh, TIL placeWithLayer 🙂 I figured there had to be a more sane way 🙂