简体   繁体   中英

Why isn't conversion from dp to px precise?

I'm trying to draw a black rectangle that covers the yellow Box composable , After converting the size to pixels . The Box is still slightly visible underneath. Is there a way around this?

val size = 50.dp
Box(
    modifier = Modifier
        .size(size)
        .background(color = Color.Yellow)
        .drawWithContent {
            val sizePx = size.toPx()
            drawRect(
                color = Color.Black,
                size = Size(width = sizePx, height = sizePx)
            )
        }
)

在此处输入图像描述

Dp to px conversion is dp.value * density and it's precise. However Modifier.layout or Layout returns dimensions in Int while conversion dpSize.toPx() and you can use dpSize.roundToPx() for Int conversion.

On my device

var text by remember { mutableStateOf("") }
val dpSize = 50.dp
Box(
    modifier = Modifier
        .size(dpSize)
        .background(color = Color.Yellow)
        .drawWithContent {
            val sizePx = dpSize.toPx()
            text = "drawWithContent: density: $density, dpSize in px: $sizePx, drawScope size: ${size.width}\n"
            drawRect(
                color = Color.Black,
                size = Size(width = sizePx, height = sizePx),
            )
        }


) 

Text(text = text)

在此处输入图像描述

When you draw anything inside DrawScope if you are going to draw anything that covers your Composable you don't need to pass a size.

You can use DrawScope.size. Same goes for pointerEvents either. inside pointer scope and draw scope you can get size without any extra work.

The issue you faced might be a preview bug. Even if it wasn't precise size you get from conversion is bigger than Composable size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM