Member-only story

Draw Line With Canvas In Jetpack Compose.

Jayant Kumar🇮🇳
6 min readNov 14, 2023

Photo by Nadine Shaabana on Unsplash

Link For Non-Members

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.

Canvas takes two parameters , modifier & extension function of DrawScope , which has lots of options to create custom layouts, drawLine is one of them.

drawLine takes three mandatory parameters , start , end , color . As you remember i said above , for drawing line , we have to create two points(A,B).

start -> A Point

end -> B Point

Suppose I want to draw a line to the vertically centre of the screen. The first point will be at the CentreStart and another point will be at the CentreEnd .

Let’s first come at the CentreStart position , start takes Offset(x,y) parameter in it.

If we pass X to positive value it will move to the right direction and if we pass Y to positive value it will move to the bottom direction. By default x and y at the (0,0) position.

Jayant Kumar🇮🇳
Jayant Kumar🇮🇳

Written by Jayant Kumar🇮🇳

Hello My name is Jayant Kumar, I am a software Engineer , specialist in Mobile Development (Android , IOS , Flutter , React Native) from India 🇮🇳

No responses yet

Write a response