
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:

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:

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:

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:

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:

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:

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.
You have save my life! Keep up the good work