Saturday, March 6, 2010

Draw Bar Graph In C#

//Posted By Suresh Chand Jangid
// A procedure which is get three perameter and return a Bar graph
//1 strTitle - Tile of graph
//2 aX - Array list of X axis
//3 aY - Array list of Y axis



public void DrawBarGraph(string strTitle, ArrayList aX, ArrayList aY)
{
const int iColWidth = 15, iColSpace = 25, iMaxHeight = 400, iHeightSpace = 25, iXLegendSpace = 30, iTitleSpace = 50;

int iMaxWidth = (iColWidth + iColSpace) * aX.Count + iColSpace, iMaxColHeight = 0, iTotalHeight = iMaxHeight + iXLegendSpace + iTitleSpace;

Bitmap objBitmap = new Bitmap(iMaxWidth, iTotalHeight);
Graphics objGraphics = Graphics.FromImage(objBitmap);

objGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, iMaxWidth, iTotalHeight);
objGraphics.FillRectangle(new SolidBrush(Color.Ivory), 0, 0, iMaxWidth, iMaxHeight);

// find the maximum value
//int iValue;
foreach(int iValue in aY)
{
if(iValue > iMaxColHeight) iMaxColHeight = iValue;
}
int iBarX = iColSpace, iCurrentHeight;
SolidBrush objBrush = new SolidBrush(Color.FromArgb(70, 20, 20));
Font fontLegend = new Font("Arial", 11), fontValues = new Font("Arial", 8), fontTitle = new Font("Arial", 14);

// loop through and draw each bar
int iLoop;
for(iLoop = 0; iLoop <= aX.Count - 1;iLoop++)
{
iCurrentHeight = Convert.ToInt32( ((Convert.ToDouble(aY[iLoop]) / Convert.ToDouble(iMaxColHeight)) * Convert.ToDouble(iMaxHeight - iHeightSpace)));
objGraphics.FillRectangle(objBrush, iBarX, iMaxHeight - iCurrentHeight, iColWidth, iCurrentHeight);
objGraphics.DrawString(aX[iLoop].ToString(), fontLegend, objBrush, iBarX, iMaxHeight);
objGraphics.DrawString(aY[iLoop].ToString(), fontValues, objBrush, iBarX, iMaxHeight - iCurrentHeight - 15);
iBarX += (iColSpace + iColWidth);
}
objGraphics.DrawString(strTitle, fontTitle, objBrush, (iMaxWidth / 2) - strTitle.Length * 6, iMaxHeight + iXLegendSpace);
//objBitmap.Save("C:\inetpub\wwwroot\graph.gif", ImageFormat.GIF)
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
objGraphics.Dispose();
objBitmap.Dispose();
}

No comments:

Post a Comment