I want to get the size of a composable I’m current...
# compose
s
I want to get the size of a composable I’m currently in, is there a way to do this “inline” without doing something that moves this to the next frame? Say I got a state like this
Copy code
var width by remember { mutableStateOf(0f) } // 0f or 0 or 0.dp not sure what I need yet
var height by remember { mutableStateOf(0f) }
Canvas can get you a size but can only set it on the next frame to the local state as I understand.
Copy code
Canvas(Modifier.fillMaxSize()) {
  width = this.size.width
  height = this.size.height
}
OnGloballyPositioned also on the next frame
Copy code
.onGloballyPositioned { it.size.height | width }
BoxWithConstraints uses subcomposition. My use case is trying to get the bounds of my Canvas in order to animate something that’s moving inside of it and make sure it’s not going outside. What other options do I have? Or is getting it from canvas and saving it to a local state the way to go? Also what if I was not using a Canvas anyway, what other alternatives are there?
m
Modifier.onPlaced {}
should give you the coordinates directly after the parent is placed https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]Samp&ss=androidx%2Fplatform%2Fframeworks%2Fsupport:compose%2F, not sure if there is another API that can give you coordinates earlier than that
s
Awesome thanks for the link! I think this is what I was looking for