In this post I shall be writing about how you can create a pie chart view by drawing on Canvas.
Without wasting any more time lets start.
First thing that we have to do is to create a new view class lets call it PieChartView and extend with View class.
Now, I will be drawing each section of pie chart with a different colour, so I also create an array of few colour codes.
We will also require a Paint object, so lets do that too.
Besides all these lets create a 2 Dimensional array of App Name, and the Percentage. This will serve as a dummy data to plot.
So our code will look like this now:
Now lets override onSizeChanged(int nw, int nh, int ow, int oh) method. Here we will initialize paint object, create a Rectangle object, within which we will draw, and select dimension for circle, whose width and height will be same.
Lets create two other methods, setTextSize & setData, we will need them later on.
So now our code looks like this:
All small things are set now, its time to override the onDraw method now.
Here is what we will do to draw arc:
- Go through each data that will be drawn.
- For the percentage calculate how many degrees will it cover.
- For every section, calculate start & end degree.
- Draw Arc using these degrees.
Next is to write text. These are the things which shall be done for same.
- Go through each data that will be drawn.
- For the percentage calculate how many degrees will it cover.
- Convert degrees to radian, since Java Sin, Cos classes work on Radian.
- For each degree calculate the point that will lie on arc, below is the diagram to understand the same.
- Calculate the width of text and subtract that from X coordinate while drawing.
- Similarly adjust the height of it.
Here is the diagram to understand the coordinate from degree.
So finally our code looks like this:
And here is how our Pie Chart looks like.
Hope you liked it.
Please do follow me on facebook too.