Home > Software design >  Unexpected border in Composables. Border shows even if border width is Zero.?
Unexpected border in Composables. Border shows even if border width is Zero.?

Time:06-08

I have created a custom composable to show text inside a Box. Even if I specified border width as Zero with modifier, composable still show a thin border. Any idea why composable (or modifier) behaves this way?

Composable Code

@Composable
fun TextBox(
    modifier: Modifier = Modifier,
    backgroundColor: Color = Color.Yellow,
    borderWidth: Dp = 0.dp,
    borderColor: Color = Color.Black
) {
    Box(
        modifier = modifier
            .background(backgroundColor)
            .border(
                width = borderWidth,
                color = borderColor
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "EXPLORE")
    }
}

Preview Code

@Preview(showBackground = true)
@Composable
fun TextBoxPreview() {
    TextBox(
        modifier = Modifier
            .fillMaxWidth()
            .height(75.dp)
            .padding(16.dp),
        backgroundColor = Color.Yellow,
        borderWidth = 0.dp,
        borderColor = Color.Black
    )
}

Output Preview

Output Preview from Peview panel

CodePudding user response:

In Border.kt, we can see this method,

fun Modifier.border(width: Dp, brush: Brush, shape: Shape): Modifier = composed(
    // irrelevant code
    val hasValidBorderParams = width.toPx() >= 0f && size.minDimension > 0f
    if (!hasValidBorderParams) {
        drawContentWithoutBorder()
    } else {
    val strokeWidthPx = min(
        if (width == Dp.Hairline) 1f else ceil(width.toPx()),
        ceil(size.minDimension / 2)
    )
    // irrelevant code
    }
    // irrelevant code
}

And for Dp.Hairline.

val Hairline = Dp(value = 0f)

So, providing a border width of 0.dp creates a border of 1px.


If we want to hide the border conditionally,
we can use a Transparent color for the border based on width.

.border(
    width = borderWidth,
    color = if (borderWidth == 0.dp) {
        Transparent
    } else {
        borderColor
    },
),
  • Related