Tuesday, December 18, 2012

Pie Graph in BlackBerry , Android and J2ME

1) Define array of data and array of colors.


int[] data = { 16, 14, 16, 10, 4 };
int colors[] = { Color.RED , Color.LIGHTBLUE ,Color.YELLOW, Color.GREEN,Color.BLUE};

/////////////////////
2) Other parameters

int width = 200; // width of area where pie graph is drawn.
int height = 200; //height of area where pie graph is drawn.
int sum = 0;
   
int deltaAngle ;
int x = 0; //starting point where area of pie graph drawn (you can change this as per your choice)
int y = 0; //
int diameter;
//////////////////////

3)Calculation

 sum = 0;
    for (int i = 0; i < data.length; i++) {
      sum += data[i];
    }
    deltaAngle = 360 * 100 / sum / 100;
   

    if (width > height)
      diameter = height - y * 2;
    else
      diameter = width - x * 2;
/////////////////
4)Paint function

protected void paint(Graphics graphics) {

    graphics.setColor(Color.BLACK);
    graphics.fillRect(0, 0, width, height);
    graphics.clear();
   
    int startAngle = 0;

    for (int i = 0; i < data.length; i++) 
   {
      graphics.setColor(colors[i]);

      graphics.fillArc(x, y, diameter, diameter, startAngle, deltaAngle * data[i]);

      startAngle += deltaAngle * data[i];
     
    }
 
}





1 comment: