How to have dashed border in Jetpack Compose?

Viewed 4140

I can easily create a normal border using the Modifier.border() but how to create a dashed border as shown in the image below.

enter image description here

3 Answers

There isn't a built-in Modifier.border() with a dash path.

However you can use the PathEffect.dashPathEffect in a Canvas.
Something like:

val stroke = Stroke(width = 2f,
    pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)

Box(Modifier.size(250.dp,60.dp),contentAlignment = Alignment.Center){
    Canvas(modifier = Modifier.fillMaxSize()) {
        drawRoundRect(color = Color.Red,style = stroke)
    }
    Text(
        textAlign = TextAlign.Center,text = "Tap here to introduce yourseft")
}

enter image description here

If you want rounded corner just use the cornerRadius attribute in the drawRoundRect method:

drawRoundRect(color = Color.Red,style = stroke,
            cornerRadius = CornerRadius(8.dp.toPx()))

enter image description here

I wrote this extension for the Modifier you can simply use it or modify it.

fun Modifier.dashedBorder(width: Dp, radius: Dp, color: Color) = 
    drawBehind {
        drawIntoCanvas {
            val paint = Paint()
                .apply {
                    strokeWidth = width.toPx()
                    this.color = color
                    style = PaintingStyle.Stroke
                    pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
        }
        it.drawRoundRect(
            width.toPx(),
            width.toPx(),
            size.width - width.toPx(),
            size.height - width.toPx(),
            radius.toPx(),
            radius.toPx(),
            paint
        )
    }
}
Related