5

I know how to get the X,Y coordinates of a button/or component, but I want to know every corner offset or at least the right bottom offset. For example I'm getting the left top coordiantes from:

Modifier.onGloballyPositioned{
    it.positionInRoot().x
    it.positionInRoot().y
}

enter image description here

Is there a way to know bottom right coordinates so I can calculate the difference offset inside the component?

Edit: Possible solution -> use spacer next to the component: Let's imagine that we want to get the right bottom of a button.

Row(
    horizontalArrangement = Arrangement.Center,
    modifier = Modifier
        .fillMaxWidth()
    ) {
        Button(
            modifier = Modifier
                        .onGloballyPositioned {
                            it.positionInRoot().x
                            it.positionInRoot().y
                         }
         ) {...}
         Row(modifier =Modifier.fillMaxHeight(),verticalAlignment = Alignment.Bottom) {
              Spacer(
                  Modifier
                   .height(0.dp)
                   .width(0.dp)
                   .onGloballyPositioned {
                       it.positionInRoot().x
                       it.positionInRoot().y
                   }
              )
          }
    }
Barrufet
  • 495
  • 1
  • 11
  • 33

2 Answers2

9

Looks like you're looking for LayoutCoordinates.boundsInRoot()

Modifier.onGloballyPositioned { layoutCoordinates ->
    val rect = layoutCoordinates.boundsInRoot()
    println("${rect.topLeft} ${rect.bottomRight}")
}

Most of time you don't need that for layout in Compose

You can place both canvas and your view in a Box, add matchParentSize modifier to your canvas and it'll be same size as your view. Inside Canvas you can use parameters like size, center, etc values to draw

Box {
    Canvas(Modifier.matchParentSize()) {
        // here you can access size, center, etc
        drawRect(Color.Green)
    }
    Text("hello")
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • 1
    @Barrufet I've updated my answer, because most probably you actually don't need to use `onGloballyPositioned` – Phil Dukhov Aug 20 '21 at 09:27
  • Damn I'm new to canvas and I didn't know about this, thank you for updating it, definitely helps a lot :) – Barrufet Aug 20 '21 at 09:43
2

You could also do this with drawWithContent().

Modifier.drawWithContent {
    //Here you can access 'size', offset starts from (0f,0f)
    print("Bottom Right ${this.size.height} , ${this.size.width}")
}
Sreekant Shenoy
  • 1,420
  • 14
  • 23