Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the width and height in Jetpack Compose View

I try to get the width and height in Jetpack Compose View. I use the below method

fun Greeting() {
    val configuration = LocalConfiguration.current
    val width = configuration.screenWidthDp.dp
    Column {

        Canvas(modifier = Modifier
            .padding(16.dp)
            .fillMaxWidth()
            .height(200.dp)
            .background(Color.Yellow)) {
            drawPath(Path().apply {
                lineTo((width.toPx() - 32.dp.toPx()), 200.dp.toPx())
            }, Color.Black, style = Stroke(2.dp.value))
        }
    }
}

Notice I have to explicitly (width.toPx() - 32.dp.toPx() to draw the line to the end of my Canvas, as I have to manually subtract the padding on both ends.

Is there a way I can get the width of the Compose Canvas view, without manually subtracting the 32.dp padding?

like image 668
Elye Avatar asked Oct 14 '25 09:10

Elye


1 Answers

you can get your composable width and height simply using Modifier.onGloballyPositioned here is the sample:

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

SomeComposable(
  modifier = Modifier.width().height()
      .onGloballyPositioned {
          size = it.size
      }

and you can change the size to Dp with this method

@Composable
fun Int.pxToDp() = with(LocalDensity.current) { 
    [email protected]() 
}

use this method like this:

Modifier.width(pxValue.pxToDp())
like image 108
MohammadBaqer Avatar answered Oct 18 '25 03:10

MohammadBaqer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!