After developing a translation of LinkLite for Android, I decided to share with you my experience in this area by publishing the java class used to draw a graph (pie chart). This article is the second of a two-part series on this subject. The first dealing with the java class to draw a line chart.
First talk, the class defining the type of data to draw:
package com.gafmedia.Graph;
package com.gafmedia.Graph;
public class PieItem {
public int Count;
public String Label;
public float Percent;
public int Color;
}
In the case of our application, we have:
Count : Represents the number to display in our pie, knowing that it will be divided by the total number to form the percentage.
Label : The title of the portion of the pie.
Percent : The percentage of the total. (Not used yet!).
Color : The color of the portion of pie.
A graph is composed of several points, they will be placed in an array of type:
List<PieItem> PieData = new ArrayList<PieItem>(0);
To fill this table you can use, for example, a loop like this:
...
PieItem Item;
Random mNumGen = new Random();
int MaxPieItems = mNumGen.nextInt(20);
int ItemValue;
//-----------------------------------------------------------
// MaxCount nous servira plus tard et représente la somme
// de tous les ItemValue pour calculer le pourcentage.
//-----------------------------------------------------------
int MaxCount = 0;
for (int i = 0; i < MaxPieItems ; i++) {
ItemCount = mNumGen.nextInt(256);
Item = new PieItem();
Item.Count = ItemCount
Item.Label = "Valeur " + mNumGen.nextInt(1000);
Item.Color = 0xff000000 + 256*256*mNumGen.nextInt(256) + 256*mNumGen.nextInt(256) + mNumGen.nextInt(256);
PieData.add(Item);
MaxCount += ItemCount;
}
...
Once your table is full, you create your graph to handle it as follows:
... //----------------------------------------------- // OverlayId =>Image qui sera dessinée au dessus // du camembert pour le rendre plus jolie !!! //----------------------------------------------- int OverlayId = R.drawable.cam_overlay_big; View_PieChart PieChartView = new View_PieChart( this ); PieChartView.setLayoutParams(new LayoutParams(Size, Size)); PieChartView.setGeometry(Size, Size, 5, 5, 5, 5, OverlayId); PieChartView.setSkinParams(BgColor); PieChartView.setData(data, MaxCount); PieChartView.invalidate(); ...
Explanation of used methods:
public void setGeometry(int width, int height, int GapLeft, int GapRight, int GapTop, int GapBottom, int OverlayId) {
...
}
This method defines the geometric parameters of your View: Size (width, height) of your View, and then the border settings (GapLeft, GapRight, GapTop, GapBottom) and finally
(OverlayId) the ID of an image will be placed on top of pie, to improve the rendering. This method is called before anything else!.
public void setSkinParams(int bgColor){
...
}
The second method is called, defines the different display settings (bgColor) background color.
public void setData (List<PieItem> data, int MaxConnection) {
..
}
The last method defined values of the graph, and the number used to calculate the maximum percentage of each share. Calling this method unlocks the method OnDraw(), avoiding throwing
an exception if the data are not defined.
Finally, here is the class View_PieChart.java, to include in your application:
package com.gafmedia.Graph;
import com.gafmedia.Graph.PieItem;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.BitmapFactory.Options;
import android.util.AttributeSet;
import android.view.View;
public class View_PieChart extends View {
private static final int WAIT = 0;
private static final int IS_READY_TO_DRAW = 1;
private static final int IS_DRAW = 2;
private static final float START_INC = 30;
private Paint mBgPaints = new Paint();
private Paint mLinePaints = new Paint();
private int mOverlayId;
private int mWidth;
private int mHeight;
private int mGapLeft;
private int mGapRight;
private int mGapTop;
private int mGapBottom;
private int mBgColor;
private int mState = WAIT;
private float mStart;
private float mSweep;
private int mMaxConnection;
private List<PieItem> mDataArray;
//--------------------------------------------------------------------------------------
public View_PieChart (Context context){
super(context);
}
//--------------------------------------------------------------------------------------
public View_PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
//--------------------------------------------------------------------------------------
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//------------------------------------------------------
if (mState != IS_READY_TO_DRAW) return;
canvas.drawColor(mBgColor);
//------------------------------------------------------
mBgPaints.setAntiAlias(true);
mBgPaints.setStyle(Paint.Style.FILL);
mBgPaints.setColor(0x88FF0000);
mBgPaints.setStrokeWidth(0.5f);
//------------------------------------------------------
mLinePaints.setAntiAlias(true);
mLinePaints.setStyle(Paint.Style.STROKE);
mLinePaints.setColor(0xff000000);
mLinePaints.setStrokeWidth(0.5f);
//------------------------------------------------------
RectF mOvals = new RectF( mGapLeft, mGapTop, mWidth - mGapRight, mHeight - mGapBottom);
//------------------------------------------------------
mStart = START_INC;
PieItem Item;
for (int i = 0; i < mDataArray.size(); i++) {
Item = (PieItem) mDataArray.get(i);
mBgPaints.setColor(Item.Color);
mSweep = (float) 360 * ( (float)Item.Count / (float)mMaxConnection );
canvas.drawArc(mOvals, mStart, mSweep, true, mBgPaints);
canvas.drawArc(mOvals, mStart, mSweep, true, mLinePaints);
mStart += mSweep;
}
//------------------------------------------------------
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap OverlayBitmap = BitmapFactory.decodeResource(getResources(), mOverlayId, options);
canvas.drawBitmap(OverlayBitmap, 0.0f, 0.0f, null);
//------------------------------------------------------
mState = IS_DRAW;
}
//--------------------------------------------------------------------------------------
public void setGeometry(int width, int height, int GapLeft, int GapRight, int GapTop, int GapBottom, int OverlayId) {
mWidth = width;
mHeight = height;
mGapLeft = GapLeft;
mGapRight = GapRight;
mGapTop = GapTop;
mGapBottom = GapBottom;
mOverlayId = OverlayId;
}
//--------------------------------------------------------------------------------------
public void setSkinParams(int bgColor) {
mBgColor = bgColor;
}
//--------------------------------------------------------------------------------------
public void setData(List<PieItem> data, int MaxConnection) {
mDataArray = data;
mMaxConnection = MaxConnection;
mState = IS_READY_TO_DRAW;
}
//--------------------------------------------------------------------------------------
public void setState(int State) {
mState = State;
}
//--------------------------------------------------------------------------------------
public int getColorValue( int Index ) {
if (mDataArray == null) return 0;
if (Index < 0){
return ((PieItem)mDataArray.get(0)).Color;
} else if (Index >= mDataArray.size()){
return ((PieItem)mDataArray.get(mDataArray.size()-1)).Color;
} else {
return ((PieItem)mDataArray.get(mDataArray.size()-1)).Color;
}
}
}
As always, you can download all files HERE .
(14-12-2010) UPDATE :
I add an ANDROID sample with this class, you can download it HERE.


Thx all, you’re welcome !
This blog is under construction, and it will be more designed and updated soon…
Can you tell me what type of image I need to use for the OverlayId? I mean… is this a transparent image that is rendered over the top of the pie chart or what?
Yes it is a transparent image like http://blog.gafmediastudio.com/wp-content/uploads/cam_overlay.png
how can i call this pie chart class ..need click event or what ??
I don’t understand your question ??? it is a view class…. and it can be used like a view class… no click event needed !!!
thanks for reply,
i misunderstood..its a view class u right
great post
thanks.
Hi. Very interesting Blog. Not really what i have searched over Google, but thanks for the information.
I was trying the snippets from your code above. I am facing a slight problem.
I have used a relative layout, and have placed as marker for pie chart. I am trying to do tablerow.addview(piechart);
The pie chart is drawn but then after around 1 second it disappears. Could you suggest a possible fix?
Figured the thing out, I was passing it before instantiating it
Thank you for this post. Exactly what I was looking for!
I have the same problem…the pie chart is drawn but then after around 1 second it disappears.
How can i fix this?
Thanks
Look at the variable mState ! after draw it must be set with IS_DRAW value. Otherwise the procedure OnDraw is call and may drawing a blank canvas.
To be on the matches you need to do all this in this order:
View_PieChart PieChartView = new View_PieChart( this );
PieChartView.setLayoutParams(new LayoutParams(Size, Size));
PieChartView.setGeometry(YourSize, YourSize, 5, 5, 5, 5, YourOverlayId);
PieChartView.setSkinParams(YourBgColor);
PieChartView.setData(Yourdata, YourMaxCount); // in last it’s very important !!!
PieChartView.invalidate();
Actually if I try to run it again, then it will draw on the same canvas, means piechart is drawn on the already drawn piechart.How can I remove this problem.
Where do i use View_PieChart class??
Can anybody help?
Hi, i am new to android. Can anybody give complete source code? I dont know how to use View_PieChart class.
I will tell where u can use this pie chart…
can you tell me how to use View_PieChart class,i used it but i run mistakes. thank you
Ok, I’ll make an ANDROID sample for this class! give me a few days to do!
Update 14-12-2010 :
You can found an ANDROID sample for this class above !
Hi, I can draw pie chart. But now i want to show legend in pie chart. Can anybody help?
To do your request you can add this code after the draw loop on View_PieChart class
//------------------------------------------------------------
// Draw Legend on Pie
//------------------------------------------------------------
mStart = START_INC;
float lblX;
float lblY;
String LblPercent;
float Percent;
DecimalFormat FloatFormatter = new DecimalFormat("0.## %");
float CenterOffset = (mWidth / 2); // Pie Center from Top-Left origin
float Conv = (float)(2*Math.PI/360); // Constant for convert Degree to rad.
float Radius = 2 *(mWidth/2)/ 3; // Radius of the circle will be drawn the legend.
Rect bounds = new Rect();
for (int i = 0; i < mDataArray.size(); i++) {
Item = (PieDetailsItem) mDataArray.get(i);
Percent = (float)Item.Count / (float)mMaxConnection;
mSweep = (float) 360 * Percent;
// Format Label
LblPercent = FloatFormatter.format(Percent);
// Get Label width and height in pixels
mLinePaints.getTextBounds(LblPercent,0,LblPercent.length(),bounds);
// Claculate final coords for Label
lblX = (float) ((float) CenterOffset + Radius*Math.cos( Conv*(mStart+mSweep/2)))- bounds.width()/2;
lblY = (float) ((float) CenterOffset + Radius*Math.sin( Conv*(mStart+mSweep/2)))+ bounds.height()/2;
// Dwraw Label on Canvas
canvas.drawText(LblPercent, lblX , lblY , mLinePaints);
mStart += mSweep;
}
One more thing !!!
If you want stretch the overlay image you can use this code :
//------------------------------------------------------------
// Resize Overlay Image to fit with Pie Size
//------------------------------------------------------------
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap OverlayBitmap = BitmapFactory.decodeResource(getResources(), mOverlayId, options);
//-----------------------------------------------
// Added code Begin
//-----------------------------------------------
int width = OverlayBitmap.getWidth();
int height = OverlayBitmap.getHeight();
int newWidth = mWidth;
int newHeight = mWidth;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(OverlayBitmap, 0, 0,width, height, matrix, true);
//-----------------------------------------------
// End Added code
//-----------------------------------------------
canvas.drawBitmap(resizedBitmap, 0.0f, 0.0f, null);
Hi,I can draw pie chart with legend.But i want to show data in pie chart.Can anybody help?
thanks a lot. it shows percentage of pie chart. but i need to show legend of pie chart area below the chart. is there any possibilities to show legend below the chart in a same view? or any other options to show the legend?
I solved my legend problem. i can draw legend below the pie chart using below code.
canvas.drawCircle(30, 140, 5, textPaint);
canvas.drawText(« Pie Chart », 40, 140, textPaint);
where textPaint is Paint Object.
Thanks a lot for repling my question..
You are welcome !!!
How to Re size the Pie Chart?I can show pie chart.But its size is very small.But i want big size with Center.Can anybody help please?
Have you open the app code source with Eclipse ??? it is documented !!!
//——————————————————————————————
// Size => Pie size
//——————————————————————————————
int Size = 150;
If you resize the chart, use the « Resize Overlay Image » code above !
How to increase Pie chart size as big with OverlayId?Can anybody help please?
how to set constant color to item in pie chart.While running application different colors are coming.Can anybody help please?
Hi,
Anyone can help? Can I know how to set the pie chart to a report with daily, weekly & monthly based on the statistic from the database. How?
I only manage to have the auto generated pie chart when I open the application.
I am trying to make the graph click able and show some details of the particular sector/pie which was clicked by the user. Please can anyone help me in this regard.
thx .great article..
and i have a question:
what’s the purpose of « Draw Pie Vien on Bitmap canvas »from the sample ?
(though i just new PieChartView and add it to root view.the code running well)
and thx again for your share
You’re right, it works too!
Hi,
Can i get a sample code to draw a bar chart frm an xml file
I know how to parse and i hav all my data in arraylist.Plz help me out
please
how do I create a label on the pie chart for percentage text
how to add button in pie chart view
i am new user, i want to use these View_PieChart.class file but prob is from where to call these class in my activity.
like from where to call these view class
in onCarete() or elsewhere…
please rplay with code
Hi, first of all thanks for this valuable blog.
Now what i m looking for, i want to use this chart in my app to show two field. like storage device…. that is used and un-used space in percentage. for that i need only two color and 2 filed, nothing else, and the percentage of storage i have to set at run time, please help me out.
Thanks in advance
cheers
Piyush palod
This is a very good tutorial. And thanks for providing the source code.
Hi want use some of this library but i want populate mi graphs with values of a data base in SQlite some body can helpme
Thanks for sharing this information! It really helped me a lot in a school project.
Why do I need an overlay image – this part I didn’t quite get, but I’m sure google will be a lot of help.
good example for piechart.it,s very useful for me.
And one more question I am trying to make the graph click able and show some details of the particular sector/pie which was clicked by the user. Please can anyone help me in this regard.
I like this type of pie chart. Looks very nice on my phone. I have a problem though. I have 8 databases and I need them represented in a pie. The values of d1,d2,d3,d4,d5,d6,d7,d8 (the databases) are already passed into respective variables that automatically update their values if something is added or subtracted from the original databases.
What I need help with is how to implement the variables (doubles) of those 8 databases into the chart to show it. I’ve tried modifying the code to do so, but can’t figure it out… Thanks in advance!
[...] Here is the link to the chart and tutorial: http://blog.gafmediastudio.com/2010/04/01/draw-a-pie-chart-with-android/ [...]