I can easily create a normal border using the Modifier.border() but how to create a dashed border as shown in the image below.
I can easily create a normal border using the Modifier.border() but how to create a dashed border as shown in the image below.
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")
}
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()))
After some digging in the normal border modifier, I found out that it uses Stroke object which can take a parameter PathEffect that can make it dashed, here is a modified version of the normal border function that takes this parameter.
https://gist.github.com/DavidIbrahim/236dadbccd99c4fd328e53587df35a21
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
)
}
}