https://www.cnblogs.com/zhaotianff/p/16481443.html
private void button4_Click(object sender, EventArgs e)
{
string dataName = "a,b,c,d,e";
string dataValue = "1,1,1,1,1";
Color[] colors = new Color[5];
colors[0] = Color.Red;
colors[1] = Color.Yellow;
colors[2] = Color.Green;
colors[3] = Color.Gray;
colors[4] = Color.Lavender;
Image image= DrawEllipse(300, dataName, dataValue, colors);
image.Save("pile.png");
}
//绘制饼形图
static public Image DrawEllipse(int imageWidth, string DataName, string DataValue, Color[] colors)
{
//string dataName = "a,b,c,d,e";
//string dataValue = "6,2,3,9,3";
string dataName = DataName;
string dataValue = DataValue;
int dataValueSum = 0;
int dataCnt = dataName.Split(',').Length;
float[] arrDataPercentage = new float[dataCnt];
string[] arrDataName = new string[dataCnt];
int[] arrDataValue = new int[dataCnt];
Random rand = new Random();
arrDataName = dataName.Split(',');
for (int i = 0; i < dataCnt; i++)
{
arrDataValue[i] = Convert.ToInt32(dataValue.Split(',')[i]);
dataValueSum += arrDataValue[i];
}
for (int i = 0; i < dataCnt; i++)//计算百分率
{
arrDataPercentage[i] = Convert.ToSingle(arrDataValue[i]) / dataValueSum;
}
//int imgWidth = 400, imgHeight = 600;
int imgWidth = imageWidth;
Image image = new Bitmap(imgWidth + 20 * dataCnt + 5, imgWidth);
//BorderStyle
Rectangle rectBorder = new Rectangle(1, 1, imgWidth -3, imgWidth -3);
Rectangle rectBorder2 = new Rectangle(1, 1, imgWidth +120, imgWidth - 3);
Pen borderColor = new Pen(Color.Gray);
//PieStyle
SolidBrush[] arrbrush = new SolidBrush[dataCnt];
for (int i = 0; i < dataCnt; i++)
{
arrbrush[i] = new SolidBrush(colors[i]);
// arrbrush[i] = new SolidBrush(Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)));
}
//startGraphics
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//GraphicsLine
g.DrawRectangle(borderColor, rectBorder);
g.DrawRectangle(borderColor, rectBorder2);
//GraphicsPie
float startPosition = 0.0f;
Rectangle rectPie = new Rectangle(rectBorder.Location.X + 2, rectBorder.Location.Y + 2, rectBorder.Width - 4, rectBorder.Height - 4);
for (int i = 0; i < dataCnt; i++)
{
g.FillPie(arrbrush[i], rectPie, startPosition, arrDataPercentage[i] * 360);
startPosition += arrDataPercentage[i] * 360;
}
//GraphicsString
for (int i = 0; i < dataCnt; i++)
{
g.FillRectangle(arrbrush[i], new Rectangle( 10+ rectBorder.Width , (i+1) * 40, 30, 20));
string str = string.Format("{0}——{1:p}", arrDataName[i], arrDataPercentage[i]);
g.DrawString(str, new Font("", 9), arrbrush[i], new Point(10 + rectBorder.Width +40 , (i + 1) * 40 ));
}
return image;
}