Search code examples
androidkotlinandroid-studioandroid-jetpack-composeandroid-jetpack-compose-material3

Draw border to column on every side but in top Jetpack Compose


I have a Column with a border like this

Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .border(
                    width = 2.dp,
                    color = colorResource(R.color.appGreen)
                )
        )

That adds border to every side but I don't want to have border on the top, only want it on bottom, left and right. Something like this:

enter image description here

Hoe can I do this?? Thanks


Solution

  • The border modifier doesn't offer the flexibility to exclude specific sides. Instead, you can use drawBehind to draw lines on all sides except the top.

    Here's the code for your scenario:

    Column(
            modifier = Modifier
                .padding(16.dp)
                .height(100.dp)
                .fillMaxWidth()
                .drawBehind {
                    val cap = StrokeCap.Round
                    val color = Color.Black
                    val strokeWidth = 2.dp.toPx()
                    val halfStrokeWidth = strokeWidth / 2
                    val width = size.width
                    val height = size.height
    
                    // Draw left line
                    drawLine(
                        cap = cap,
                        color = color,
                        strokeWidth = strokeWidth,
                        start = Offset(halfStrokeWidth, halfStrokeWidth),
                        end = Offset(halfStrokeWidth, height - halfStrokeWidth),
                    )
    
                    // Draw bottom line
                    drawLine(
                        cap = cap,
                        color = color,
                        strokeWidth = strokeWidth,
                        start = Offset(halfStrokeWidth, height - halfStrokeWidth),
                        end = Offset(width - halfStrokeWidth, height - halfStrokeWidth),
                    )
    
                    // Draw right line
                    drawLine(
                        cap = cap,
                        color = color,
                        strokeWidth = strokeWidth,
                        start = Offset(width - halfStrokeWidth, halfStrokeWidth),
                        end = Offset(width - halfStrokeWidth, height - halfStrokeWidth),
                    )
                }
        ) {
            // Your column content here
        }
    

    result image