Writing custom components in Compose — Part1 → Multi Color Progress Bar

Customizing ui to please ui designers is always hard. Today i am gonna show you how to write a custom progress bar with multi color.

Lets Start with creating a compose function

I have added the height as 16.dp ( This was our designer’s idea).

Now lets calculate the progress percentages

val canvasWidth = size.width.toDp()
val progressGreen = 40
val greenSize = (canvasWidth * progressGreen) / 100
val progressYellow = 20
val yellowSize = (canvasWidth * progressYellow) / 100
val progressRed = 15
val redSize = (canvasWidth * progressRed) / 100
val progressGray = 5
val graySize = (canvasWidth * progressGray) / 100

val remainingProgress = 100 — (progressGreen + progressYellow + progressRed + progressGray)
val remainingSize = (canvasWidth * remainingProgress) / 100

val cornerRadius = CornerRadius(2.dp.toPx(), 2.dp.toPx())

These progess percentages are hardcoded for the purpose of demo. You can use states and expose the percentage as mutable states as well.

The above is used to draw a green progress. We could have drawn a rectangle but we needed a rounded corner at the top left and bottom left only. But a rounded rect will have the corners at the both ends which is not what we wanted. So we decided to use path and draw them instead of rectangle. The path is also used to draw the remaining progress this time the rounded corners at the top right and bottom right.

Now you would have guessed how to draw other part of the progess with different colors.

And the result

We can customize this by passing colors and corner radius to the function rather than hard code.

Yup. That’s it. Its much easier to draw with compose compared to view based system where we need to define custom attributes and then handle different constructors for the custom view.

Part -2 Animating Progress https://raghunandan2005.medium.com/multi-color-progress-bar-part2-animating-the-progess-3ef4b4c07bf9

Note: If you find anything wrong or have better suggestions do let me know.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store