如果项目为了安全,不引入第三方dll,则可以使用Graphics自己画图,的情况下,
首先建一个实体:
public class StatCount
{
/// <summary>
/// 名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 数量
/// </summary>
public int count { get; set; }
}
从数据库中读取实体集合:
public static Image Draw(List<StatCount> list, Image imgfont, int width = 500, int height = 500)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(width, height);
//创建Graphics类对象,用来画饼状图
Graphics g = Graphics.FromImage(image);
Pen p = new Pen(new SolidBrush(Color.Blue));
Point p1 = new Point(0, 0);
Size s = new Size(width, height);
Rectangle trct = new Rectangle(p1, s);
g.FillEllipse(new SolidBrush(Color.Red), trct);
Font font = new Font("宋体", 10, FontStyle.Regular);
int total = list.Sum((w) => { return w.count; });
//写文字
Graphics gfont = Graphics.FromImage(imgfont);
int fontspan = 15;
for (int i = 0; i < list.Count; i++)
{
//画大饼
Color color = ColorIndex(i);
float f = float.Parse(list[i].count.ToString()) / float.Parse(total.ToString());
//写文字
fontspan = fontspan + 15;
//绘制小矩形
gfont.FillRectangle(new SolidBrush(color), 0, fontspan, 20, 10);
//写百分比文字
gfont.DrawString(list[i].name + " " + FormatCentStr(total, list[i].count), font, new SolidBrush(Color.Blue), 30, fontspan);
}
return image;
}
调用并测试画饼状图.
public void DrawPie()
{
//年某商品走势
List<GraPie.StatCount> list = new List<GraPie.StatCount>();
int count = GraPie.Random().Next(2, 6);
for (int i = 1; i <= count; i++)
{
list.Add(new GraPie.StatCount() { name = i.ToString() + "月", count = GraPie.Random(1, 1000) });
}
Image imgfont = new System.Drawing.Bitmap(zpictwo.Width, zpictwo.Height);
zpic.BackgroundImage = GraPie.Draw(list, imgfont, zpic.Width, zpic.Height);
zpictwo.BackgroundImage = imgfont;
}
实现效果如下: