RamaSkills
We Build Software That Ships

Creating a Custom Bar Graph with Canvas in Jetpack Compose

By RamaSkills

Learn how to create a custom bar graph using Canvas in Jetpack Compose with this step-by-step guide.

Creating a custom bar graph in an Android application can enhance the visual representation of data. This article will guide you through the process of building a simple yet effective bar graph using Canvas in Jetpack Compose. We'll cover the necessary components, how to set up your project in Android Studio, and how to render the graph step by step.

Setting Up Your Project

To get started, ensure you have Android Studio installed and create a new Jetpack Compose project. Follow these steps:

  1. Open Android Studio and select "New Project".
  2. Choose "Empty Compose Activity".
  3. Name your project and select the appropriate settings (language: Kotlin, minimum API level: 21 or higher).
  4. Click "Finish" to create your project.

Once the project is set up, you will see a basic structure in your MainActivity.kt file.

Adding Dependencies

Before we implement the bar graph, make sure you have the necessary dependencies in your build.gradle file. Add the following dependencies for Jetpack Compose:

dependencies {
    implementation "androidx.compose.ui:ui:1.1.0"
    implementation "androidx.compose.material:material:1.1.0"
    implementation "androidx.compose.ui:ui-tooling-preview:1.1.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0"
    implementation "androidx.activity:activity-compose:1.4.0"
}

Sync your project after adding the dependencies to ensure everything is up-to-date.

Creating the Bar Graph

Now that we have our project set up, we will create the bar graph using a Composable function. Here’s how to do it:

Data Model

First, we will define a data model to represent the bar graph data. For this example, we will use a simple list of integers to represent the heights of the bars.

data class BarData(val value: Float, val label: String)

Composable Function

Next, we will create a Composable function that uses the Canvas to draw the bars. Here’s the complete code for our BarGraph function:

@Composable
fun BarGraph(barData: List<BarData>, modifier: Modifier = Modifier) {
    Canvas(modifier = modifier) {
        val barWidth = size.width / barData.size
        val maxHeight = size.height

        barData.forEachIndexed { index, data ->
            val barHeight = (data.value / 100) * maxHeight // Scale the bar height
            val barX = index * barWidth
            val barY = maxHeight - barHeight

            drawRect(
                color = Color.Blue,
                topLeft = Offset(barX, barY),
                size = Size(barWidth - 10, barHeight)
            )
        }
    }
}

Rendering the Bar Graph

To render the BarGraph, we can call it from our main Composable function. Here’s how to set up a sample list of data and display the graph:

@Composable
fun MainScreen() {
    val barData = listOf(
        BarData(50f, "A"),
        BarData(75f, "B"),
        BarData(30f, "C"),
        BarData(90f, "D"),
        BarData(60f, "E")
    )

    Column {
        Text(text = "Custom Bar Graph", style = MaterialTheme.typography.h4)
        BarGraph(barData = barData, modifier = Modifier.fillMaxWidth().height(300.dp))
    }
}

Previewing Your Composable

To preview your Composable, you can add the following code snippet to ensure that it displays correctly in the Android Studio preview:

@Preview(showBackground = true)
@Composable
fun PreviewBarGraph() {
    MainScreen()
}

Running Your Application

Now that you have created the bar graph, it's time to run your application. Click on the "Run" button in Android Studio, and select an emulator or a connected device. You should see your custom bar graph displayed on the screen.

Conclusion

Creating a custom bar graph in Jetpack Compose using Canvas is a straightforward process that can significantly enhance the data visualization capabilities of your Android applications. By following the steps outlined in this guide, you can easily implement a functional and visually appealing bar graph.

For a more detailed walkthrough, you can refer to the video tutorial: Watch the full tutorial on YouTube.

This implementation can be further customized by adding colors, labels, and animations to create a more engaging user experience. Experiment with different styles and data sets to make your application stand out.

Watch the video tutorial: https://www.youtube.com/watch?v=mB4ugibJ6GY