Jetpack Compose: Pie Chart

Android-World
2 min readMay 12, 2023

Pie charts are a popular way to visualize data. They’re used to show proportions of a whole, where each slice represents a different category. In this article, we’re going to create a Pie Chart using Jetpack Compose’s Canvas, along with three different examples.

Building a PieChart Component

We will start by building a PieChart composable that accepts a list of PieChartEntry. Each PieChartEntry will have a color and a percentage that represents its share of the pie.

data class PieChartEntry(val color: Color, val percentage: Float)

fun calculateStartAngles(entries: List<PieChartEntry>): List<Float> {
var totalPercentage = 0f
return entries.map { entry ->
val startAngle = totalPercentage * 360
totalPercentage += entry.percentage
startAngle
}
}

@Composable
fun PieChart(entries: List<PieChartEntry>) {
Canvas(modifier = Modifier.size(300.dp)) {
val startAngles = calculateStartAngles(entries)
entries.forEachIndexed { index, entry ->
drawArc(
color = entry.color,
startAngle = startAngles[index],
sweepAngle = entry.percentage * 360f,
useCenter = true,
topLeft = Offset.Zero,
size = this.size
)
}
}
}
  • color: The color of the arc. This is the color of the slice.
  • startAngle: The starting angle of the arc in degrees. The angle is measured clockwise from the positive…

--

--

Android-World

Experienced Senior Android Developer with a passion for developing high-quality, user-friendly apps. https://twitter.com/MyAndroid_World