How to get the size of a Composable during runtime?

Viewed 2761

I have as an example the following Composable:

@Composable
fun CustomCanvas(
) {
   Box(
      Modifier
        .aspectRatio(1.33f)
        .fillMaxWidth())
} 

How do I know the size of this object after composition?

Why I want to know: I'm trying to resize and place images on a canvas. This requires knowing the size of the canvas. And no, I don't want to hardcode the size of the canvas. How to do this?

1 Answers

You can use the onGloballyPositioned modifier:

var size by remember { mutableStateOf(IntSize.Zero) }

Box(Modifier.onGloballyPositioned { coordinates ->
    size = coordinates.size})
{
   //...
}

Also the Canvas has a DrawScope which has the size property.

Canvas() {
    val canvasSize = size    
}
Related