How do I get the whole offset of a compose component

Viewed 1762

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
                   }
              )
          }
    }
2 Answers

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")
}

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}")
}
Related