.net绘图操作五
统计图是信息管理系统常用的功能,常用的有饼图、柱形图、拆线图等。饼图用来表示各部分比例,柱形图用来表示各部分的比较,拆线图用来表示发展趋势,另外还有其他一些具有特殊功能的图示。本小节将以二维饼图为例说明通过.NET GDI+来绘制统计图的原理。
用户可以使用FillPie来绘制饼块,多个饼块拼接在一起就形成了圆饼效果。其基本算法就是每个部分角度的计算,在总共360°的条件下,每个部分会占多少度。为了方便起见,本例的数据源采用数组,在实例应用过程中,数组数据可以来自数据库,具体代码如下:
int[] data = { 100, 200, 300, 460 };
Color[] colors = { Color.Green, Color.Blue, Color.Tomato, Color.Yellow };
//创建画布
Bitmap bm = new Bitmap(400, 400);
//绘图区
Graphics g = Graphics.FromImage(bm);
//清理绘图区填充为白色
g.Clear(Color.Black);
//在图片区写字
g.DrawString("饼图测试", new Font("宋体", 16), Brushes.Red, new PointF(5, 5));
float total = 0;
foreach (int i in data)
{
total += i;
}
float sweetAngle = 0;
float startAngle = 0;
int index = 0;
float x = 50f;
float y = 50f;
int width = 200;
foreach (int i in data)
{
sweetAngle = i / total * 360;
g.FillPie(new SolidBrush(colors[index]), x, y, width, width, startAngle, sweetAngle);
g.DrawPie(Pens.Indigo, x, y, width, width, startAngle, sweetAngle);
index++;
startAngle += sweetAngle;
}
bm.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
g.Dispose();