Home > Mobile >  Incorrect RectF On Canvas Created From Composable
Incorrect RectF On Canvas Created From Composable

Time:07-06

I'm trying to highlight a view by grabbing the layoutCoordinate from a Box using .onGloballyPositioned. I receive the following coordinates:

val viewLeft = layoutCoordinates.boundsInWindow().left
val viewTop = layoutCoordinates.boundsInWindow().top
val viewRight = layoutCoordinates.boundsInWindow().right
val viewBottom = layoutCoordinates.boundsInWindow().bottom

When I try to create a highlight with this code, it is always off by a bit:

canvas.drawRoundRect(
viewLeft,
viewTop,
viewRight,
viewBottom,
cornerRadius,
cornerRadius,
paint)

This is the result that I am getting:

enter image description here

Any idea what I may be doing incorrect? Thanks!

CodePudding user response:

layoutCoordinates.boundsInWindow() adds status bar height to coordinate. You should use layoutCoordinates.boundsInParent() to get a Composable coordinates relative to its parent's top left corner.

For instance this example

Column(modifier = Modifier.fillMaxSize()) {
    var text by remember { mutableStateOf("") }
    Spacer(modifier = Modifier.height(200.dp))
    Column(modifier = Modifier.background(Color.Green)) {
        Spacer(modifier = Modifier.height(100.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
                .background(Color.Red)
                .onGloballyPositioned { layoutCoordinates: LayoutCoordinates ->
                    text =
                        "In window: ${layoutCoordinates.boundsInWindow()}\n"  
                                "in root: ${layoutCoordinates.boundsInRoot()}\n"  
                                "in parent: ${layoutCoordinates.boundsInParent()}"
                }
        )
        Text(text)

    }
}

Red box is 100.dp below parent's top while parent is 200.dp below root's top position.

enter image description here

  • Related