2

I want to draw on Canvas based on its layout dimension, but the dimensions received from DrawScope don't match with the Canvas

@Preview
@Composable
fun Circle() {

    val modifier = Modifier
        .fillMaxSize()
        .border(1.dp, color = Color.Magenta)
        .layout { measurable, constraints ->
            val placeable = measurable.measure(constraints)
            val minDimension = min(placeable.width, placeable.height)
            Log.d("Canvas layout", "$minDimension")
            layout(minDimension, minDimension) {
                placeable.placeRelative(0, 0)
            }
        }

    Canvas(modifier) {
        Log.d("Canvas drawCircle", "${size.width}, ${size.height}")
        drawCircle(
            color = Color.White,
            center = Offset(size.minDimension/2, size.minDimension/2),
            radius = size.minDimension/2
        )
    }
}

Logcat:

D/Canvas layout: 1080
D/Canvas drawCircle: 1080.0, 1987.0

values are the same either calling fillMaxSize() at the beginning or at the end of the modifier builder, but it is 0 when not calling fillMaxSize() .

From the screenshot you can see from the border that the width and height of Canvas match but why they don't in the DrawScope, and how can I get it to match

hippietrail
  • 15,848
  • 18
  • 99
  • 158
lost bit
  • 123
  • 1
  • 8
  • Just to clarify: after `layout` you're expecting canvas size to be a square, but it's still equal to the original size (before `Modifier.layout` has being applied). I don't know why it works like this, it may be a bug, consider [asking](https://issuetracker.google.com/issues/new?component=612128) from maintainers. Also in this particular case `layout` can be replaced with `Modifier.aspectRatio(1f)`, but this doesn't solve the general problem. – Phil Dukhov Mar 31 '22 at 02:56

0 Answers0