Member-only story

Jetpack Compose Canvas (with Examples)

Kumar
4 min readNov 27, 2024

--

Android Jetpack Compose offers several APIs like Button, Switch, etc. But what if you want to create a custom UI? That’s where Canvas comes in handy. In this article, we’ll learn how to draw custom graphics in Jetpack Compose using the Canvas API.

What is Canvas?

Canvas is used to create custom UI components. You can design any kind of UI you want. Before jumping into it, we need to understand the coordinate system in Android.

Jetpack compose canvas coordinate system

The coordinate system starts at the top left corner. The corner represents the (0,0) point. The X values increase towards the right and Y values increase downwards. Everything we draw on the Canvas is relative to (0,0) point.

Let’s look at the API. It takes two parameters.

@Composable
fun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit)

The modifier is used for adding styles (like border) and onDraw is a lambda that will be called when we are drawing. Let’s create a Canvas of size 300.dp.

@Composable
fun MyUI() {
Canvas(
modifier = Modifier
.size(size = 300.dp)
.border(width = 2.dp, color = Color.Magenta, shape = RectangleShape)
) {

}
}

It looks like this:

Let’s specify the coordinates at the corners.

Let’s draw a line vertically. To draw lines, there is a drawLine() function.

@Composable
fun MyUI() {
Canvas(
modifier = Modifier
.size(size = 300.dp)
.border(width = 2.dp, color = Color.Magenta, shape = RectangleShape)
) {
drawLine(
color = Color.Blue,
strokeWidth = 2.dp.toPx(),
start = Offset(x = size.width/2, y = 0f),
end =…

--

--

Kumar
Kumar

Written by Kumar

I talk about Android and Web development.

No responses yet

Write a response