1

How to achieve the following result using Compose Canvas.

1

Sahal Nazar
  • 625
  • 4
  • 9

1 Answers1

4

You can draw these lines using simple trigonometry and drawing with Canvas, Modifier.drawWithContent or Modifier.drawWithCache.

@Composable
private fun CanvasSample() {
    Canvas(
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(1f)
    ) {
        val center = size.width / 2
        val outerRadius = center * .8f
        val innerRadius = outerRadius * .8f


        for (i in 0..360 step 30) {
            val xStart = center + (innerRadius * cos(i * DEG_TO_RAD)).toFloat()
            val yStart = center + (innerRadius * sin(i * DEG_TO_RAD)).toFloat()

            val xEnd = center + (outerRadius * cos(i * DEG_TO_RAD)).toFloat()
            val yEnd = center + (outerRadius * sin(i * DEG_TO_RAD)).toFloat()

            drawLine(
                Color.Red,
                start = Offset(xStart, yStart),
                end = Offset(xEnd, yEnd),
                strokeWidth = 3.dp.toPx(),
                cap = StrokeCap.Join
            )
        }
    }
}

const val DEG_TO_RAD = Math.PI / 180f

Image doesn't have round stroke cap, adding it will round line start and end.

enter image description here

Thracian
  • 43,021
  • 16
  • 133
  • 222