Drawing a Pie Chart Using Jetpack Compose

Ngenge Senior
2 min readAug 24, 2024

--

There are a couple of charting compose libraries but you may want to get your hands on understanding how some of the shapes are drawn. In this post, let us see how a simple pie chart can be drawn using Compose Canvas. This will be done in two parts;

  • Drawing without animations
  • Animating the draw operations

The Pie Chart Concept

A circle's total angle measure is 360 degrees and you are given a list of numeric values to draw a pie chart on paper, this is how you proceed;

  1. Calculate the sum of the values
  2. For each value, the sweep angle(circular angle it will cover) is calculated by dividing each value by the total and multiplying by 360.
  3. Draw each arc covered starting from an initial start angle.

For Compose, we will use the Canvas composable alongside the drawArc function.

Start by defining a data class to hold an Item representing a value representing values on a pie chart.

data class Item(
val name: String, val value: Float,
val color: Color
)

val sampleItems = listOf(
Item("Item 1", 2f, Color.Blue),
Item("Item 2", 4f, Color.Red),
Item("Item 3", 5f, Color.Green),
Item("Item 4", 3f, Color.Yellow),
Item("Item 5", 8f, Color.Magenta),
)

Let us proceed by drawing our pie chart.

We start with a start angle of -90 degrees and for each item on our items list, call drawArc and use its color as the color to use in drawing its arc, after each draw, add the current sweep angle to the start angle to be used as the next draw operation’s start angle. You should have the following shape.

Pie Chart

Animating the Draw Operations

For the animation, we intend to animate the sweep angle, so we will use a list of Animatable’s that will all be initialized to zero. We will then proceed by using a LaunchedEffect and animate the values to the target sweep angle for each angle. That is all the change required.

You should see this as shown in the video.

You can try switching between different animations and see the effect, and you should see a smooth transition as the chart is drawn.

--

--