Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-compose-canvas

How to make rounded corner in drawLine in jetpack compose


I am using Canvas Api to draw something. I want to draw line with rounded corner. Line is draw without any problem. But I cannot figure out which attribute for corner radius.

val boxSize = 30.dp

Box(modifier = Modifier
            .background(Color.LightGray)
            .height(height = boxSize)
    ) {
        Canvas(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            val canvasWidth = size.width
            drawLine(
                start = Offset(x = 0f, y = (boxSize / 2).toPx()),
                end = Offset(x = canvasWidth, y = (boxSize / 2).toPx()),
                color = Color.Black,
                strokeWidth = 8.dp.toPx()
            )

        }
    }

My view is simple without corner radius.

enter image description here

I want my Black line to be corner for each side with specific radius.


Solution

  • You need to add the cap argument to drawLine and set it to StrokeCap.Round.

     drawLine(
         start = Offset(x = 0f, y = (boxSize / 2).toPx()),
         end = Offset(x = canvasWidth, y = (boxSize / 2).toPx()),
         color = Color.Black,
         strokeWidth = 8.dp.toPx(),
         cap = StrokeCap.Round, //add this line for rounded edges
    )