This is the same as the Last Tutorial i have posted. We just need to implement the following code in the View instead of the last tutorial.
public class DrawBarChart extends View {
Paint paint = new Paint();
int c[] = { Color.BLUE, Color.RED };
Canvas mCanvas = new Canvas();
private float[] val_exp;
private float[] val_inco;
Context context;
WindowManager mWinMgr;
public DrawBarChart(Context context) {
super(context);
paint = new Paint();
super.draw(mCanvas);
}
public DrawBarChart(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
super.draw(mCanvas);
}
public DrawBarChart(Context context, float[] val_exp, float[] val_inco) {
super(context);
paint = new Paint();
this.val_exp = val_exp;
this.val_inco = val_inco;
super.draw(mCanvas);
}
public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float max = getMax();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = val_exp.length;
int gap = x / 12;
paint.setStyle(Style.FILL);
for (int i = 0; i < n; i++) {
paint.setColor(Color.BLACK);
//Bottom Numbers 1 to 12.
canvas.drawText("" + (i + 1), i * gap + (gap / 2), y - 5, paint);
//Vertical Lines.
canvas.drawLine((float) (i + 0.5) * gap + 4, y - 15,
(float) (i + 0.5) * gap + 4, y - 25, paint);
// Blue bars for Income.
paint.setColor(Color.BLUE);
canvas.drawLine(i * gap + 5, y - 20, (float) (i + 0.5) * gap + 3,
y - 20, paint);
float bHeIn =(max==0)?y-20: y - (val_inco[i] * (y - 22) / max)- 20;
canvas.drawRect((float) i * gap + 5, bHeIn,
(float) (i + 0.5) * gap + 3, y - 20, paint);
// Red bars for Expenses.
paint.setColor(Color.RED);
canvas.drawLine((float) (i + 0.5) * gap + 5, y - 20,
(float) (i + 1) * gap + 3, y - 20, paint);
float bHeEx =(max==0)?y-20: y - (val_exp[i] * (y - 22) / max)- 20;
canvas.drawRect((float) (i + 0.5) * gap + 5, bHeEx,
(float) (i + 1) * gap + 3, y - 20, paint);
}
}
private float getMax() {
float max = 0;
for (float f : val_exp) {
if (f > max)
max = f;
}
for (float f : val_inco) {
if (f > max)
max = f;
}
return max;
}
}
And for drawing the chart of the values of the data you need to pass the values to the objects of the class as follow.
DrawBarChart barView;
LinearLayout la;
barView = new DrawBarChart(this, vals_exp,vals_inco);
la.addView(barView);
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.