Draw Line With Canvas In Jetpack Compose.
6 min readNov 14, 2023
In this medium article we will learn how to draw line with canvas in Jetpack Compose.
So for drawing the Line through canvas , we have to create two point (A,B) , once these two point is created , your line is drawn.
1). Draw Line to the Vertically Center
@Composable
fun DrawLineVerticallyCenter(
modifier: Modifier = Modifier
) {
Canvas(
modifier = modifier
.fillMaxSize()
) {
val canvasWidth = size.width
val canvasHeight = size.height
drawLine(
start = Offset(x = 0.dp.toPx(), y = canvasHeight / 2),
end = Offset(x = canvasWidth, y = canvasHeight / 2),
color = Color.Blue,
strokeWidth = 5.dp.toPx() // instead of 5.dp.toPx() , you can also pass 5f
)
}
}
In the above code you can see , first we have to call Canvas
composable function , also width and height is mandatory (for now given fillMaxSize()).
Inside this canvas we will draw our line , while drawing line we have to find the width
and height
of the canvas.