asp.net|統計|圖表
前段時間項目需要,寫了一個簡單的表徵圖統計類.決定以後寫點東西到Blog來.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace CrystalReportsDemo
...{
/**//// <summary>
/// createReport繪製圖形報表-柱圖。
/// </summary>
public class createReport
...{
public createReport()
...{
//
// TODO: 在此處添加建構函式邏輯
//
}
public Bitmap CreatePictureReport(string[] x,int[] y,string ReportName)
...{
if(x.Length != y.Length)
...{
throw new Exception("X和Y數目不一致");
}
int colNum=y.Length;
int colScale=880/(colNum+1);
Bitmap bmp = new Bitmap(900,700,PixelFormat.Format24bppRgb);
Graphics dc = Graphics.FromImage(bmp);
dc.FillRectangle(new SolidBrush(Color.White),0,0,900,700);
Pen scalePen = new Pen(Color.Black,2);
Pen gridPen = new Pen(Color.Black,1);
dc.DrawLine(scalePen,20,680,880,680);
dc.DrawLine(scalePen,20,680,20,20);
dc.DrawLine(gridPen,20,20,880,20);
dc.DrawLine(gridPen,880,20,880,680);
Point drawPoint;
int XPoint;
int YHeight;
if(colNum==0)
...{
throw new Exception("無資料值,colNum值為0作為除數,拋出異常");
}
int drawWidth=880/(4*colNum);
//int drawWidth=580/(4*colNum+1);//4*colNum+1 確保colNum不為0.否則580/(4*0);的話會異常.0不能作為除數
int maxNum=getMaxNum(y);
Rectangle rct;
Random rnd = new Random();
int red,green,blue;
for(int i=20;i<680;i=i+96)
...{
dc.DrawLine(gridPen,20,i,880,i);
}
for(int i=0;i<colNum;i++)
...{
red=rnd.Next(0,255);
green=rnd.Next(0,255);
blue=rnd.Next(0,255);
SolidBrush brush=new SolidBrush(Color.FromArgb(red,green,blue));
XPoint=20+((i+1)*colScale)-drawWidth;
YHeight=y[i]*650/maxNum;
drawPoint=new Point(XPoint,680-YHeight);
rct=new Rectangle(drawPoint,new Size(drawWidth*2,YHeight));
dc.FillRectangle(brush,rct);
dc.DrawRectangle(gridPen,rct);
//繪製X數值
dc.DrawString(x[i],new Font("宋體",9),new SolidBrush(Color.OrangeRed),new PointF((float)(XPoint+drawWidth/2),680-YHeight/2));
//繪製Y數值
dc.DrawString(y[i].ToString(), new Font("宋體", 9), new SolidBrush(Color.Black), new PointF((float)(XPoint + drawWidth / 2), 680 - YHeight-15));
}
dc.DrawString(ReportName,new Font("宋體",10),Brushes.Black,3,3);
return bmp;
}
private int getMaxNum(int[] arr)
...{
int max=arr[0];
for(int i=1;i<arr.Length;i++)
...{
if(arr[i]>max)
...{
max=arr[i];
}
}
return max;
}
}
}