https://kotlinlang.org logo
#compose
Title
# compose
d

Denis

12/17/2020, 10:42 PM
How to properly use
Modifier.scale
(or
.graphicsLayer
with `scaleX`/`scaleY` parameters)? Here's a sample code:
Copy code
@Preview
@Composable
fun TestScale() {
    Row(Modifier.fillMaxSize()) {
        val origin0 = TransformOrigin(0f, 0f)
        Box(Modifier.graphicsLayer(scaleX = .5f, scaleY = .5f, transformOrigin = origin0)) {
            SomeComposable(Color.Cyan)
        }
        Box(Modifier.graphicsLayer(scaleX = 2f, scaleY = 2f, transformOrigin = origin0)) {
            SomeComposable(Color.Green)
        }
        Box(Modifier.graphicsLayer(scaleX = 3f, scaleY = 3f, transformOrigin = origin0)) {
            SomeComposable(Color.Yellow)
        }
    }
}

@Composable
fun SomeComposable(color: Color) {
    Box(modifier = Modifier.background(color).padding(16.dp)) {
        Text("OK")
    }
}
I want it to draw 3 boxes side-by-side but it looks like it doesn't respect scale at all. And there are those original size wireframes drawn when you hover over the the boxes. Do I need to write a custom layout or is there anything wrong with my code?
r

romainguy

12/17/2020, 10:59 PM
graphicsLayer()
gives you a hint here: you are only scaling the rendering, not the layout of your boxes
d

Denis

12/17/2020, 11:00 PM
I see. So custom layout it is?
Copy code
fun Modifier.scaleLayout(scale: Float) = Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout((placeable.width * scale).toInt(), (placeable.height * scale).toInt()) {
        placeable.placeRelative(0, 0)
    }
}
This works somehow.
Copy code
Box(Modifier
    .scaleLayout(.5f)
    .graphicsLayer(scaleX = .5f, scaleY = .5f, transformOrigin = origin0)
) {
    SomeComposable(Color.Cyan)
}
But wireframes are off