I'd need to replicate android XML view from this answer but in Jetpack Compose with pure kotlin
Asked
Active
Viewed 1.1k times
2 Answers
45
You can simply use a Canvas
with the method drawLine
applying as pathEffect
a PathEffect.dashPathEffect
:
val pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
Canvas(Modifier.fillMaxWidth().height(1.dp)) {
drawLine(
color = Color.Red,
start = Offset(0f, 0f),
end = Offset(size.width, 0f),
pathEffect = pathEffect
)
}
You can also apply the same pathEffect to other method as:
val stroke = Stroke(width = 2f,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)
Canvas(Modifier.fillMaxWidth().height(70.dp)){
drawRoundRect(color = Color.Red,style = stroke)
}

Gabriele Mariotti
- 320,139
- 94
- 887
- 841
-
how about the dot effect :/ – Amin Keshavarzian Mar 03 '22 at 20:33
-
1val pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) drawLine( color = Color.Gray, start = Offset(0f, 0f), end = Offset(0f, size.height), pathEffect = pathEffect ) in case anyone looking for a vertical line using canvas function – Rax Jul 12 '23 at 12:09
29
You can create a shape in Jetpack Compose like this:
private data class DottedShape(
val step: Dp,
) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
) = Outline.Generic(Path().apply {
val stepPx = with(density) { step.toPx() }
val stepsCount = (size.width / stepPx).roundToInt()
val actualStep = size.width / stepsCount
val dotSize = Size(width = actualStep / 2, height = size.height)
for (i in 0 until stepsCount) {
addRect(
Rect(
offset = Offset(x = i * actualStep, y = 0f),
size = dotSize
)
)
}
close()
})
}
Usage:
Box(
Modifier
.height(1.dp)
.fillMaxWidth()
.background(Color.Gray, shape = DottedShape(step = 10.dp))
)
Result:

Phil Dukhov
- 67,741
- 15
- 184
- 220
-
-
2@AminKeshavarzian just redefine dotSize with `Size(width = size.height, height = size.height)` and use rounded rect instead of a plain one – Phil Dukhov Mar 05 '22 at 15:50
-
1Philpp I have voted your answer back then, could you add now a solution below for a vertical line? – F.Mysir Jul 22 '22 at 14:55
-