How to Draw a Circle in Jetpack Compose Canvas?

jetpack compose draw circle

Today, we will learn how to draw a circle in Jetpack Compose using the drawCircle method of Canvas.

Prerequisites:

Note: Instead of Canvas, you can create circles using the Box and Shape APIs.

First, let’s draw a canvas of size 300.dp.

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

Output:

Canvas dp

Let’s draw a simple circle:

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

Output:

Simple Circle

It looks too big. We can change its size by using the radius parameter.

@Composable
fun MyUI() {
    Canvas(
        modifier = Modifier
            .size(size = 300.dp)
            .border(color = Color.Magenta, width = 2.dp)
    ) {
       drawCircle(
           color = Color.Cyan,
           radius = 50.dp.toPx()
       )
    }
}

Output:

Radius

By default, the circle is drawn in the middle of the canvas. The center parameter can be used to adjust its position. We need to specify the position using the Offset function.

@Composable
fun MyUI() {
    Canvas(
        modifier = Modifier
            .size(size = 300.dp)
            .border(color = Color.Magenta, width = 2.dp)
    ) {
        drawCircle(
            color = Color.Cyan,
            radius = 50.dp.toPx(),
            center = Offset(x = 100.dp.toPx(), y = 100.dp.toPx())
        )
    }
}

Output:

Circle offset center

Jetpack Compose also another overload with brush parameter. We can create gradient backgrounds using it.

@Composable
fun MyUI() {
    Canvas(
        modifier = Modifier
            .size(size = 300.dp)
            .border(color = Color.Magenta, width = 2.dp)
    ) {
        drawCircle(
            brush = Brush.horizontalGradient(colors = listOf(Color.Green, Color.Yellow)),
            radius = 100.dp.toPx()
        )
    }
}

Output:

Gradient Circle

What if you want to create an outlined circle? We can use the style parameter for that.

@Composable
fun MyUI() {
    Canvas(
        modifier = Modifier
            .size(size = 300.dp)
            .border(color = Color.Magenta, width = 2.dp)
    ) {
        drawCircle(
            brush = Brush.horizontalGradient(colors = listOf(Color.Green, Color.Yellow)),
            radius = 100.dp.toPx(),
            style = Stroke(width = 8.dp.toPx())
        )
    }
}

Output:

Jetpack Compose outlined circle

This is all about Canvas drawCircle method in Jetpack Compose. I hope you have learned something new. If you have any doubts, leave a comment below.

Leave a Comment