如何基于整数值创建饼图

6

我有一些整型变量,在Visual Studio表单中需要通过它们创建一个饼图。我该如何将它们链接在一起?我似乎只能找到如何将其链接到数据库,这对我来说太复杂了。


你所说的“form”,是指Windows Forms吗?还是使用WPF? - Eduardo Wada
1
在表单上放置一个图表控件,并将其设置为显示饼图类型!图表位于工具箱的数据面板中。此外,添加命名空间 using System.Windows.Forms.DataVisualization.Charting; 以便更轻松地访问属性!您只需将整数作为系列.points.add调用中的值即可。 - TaW
是的,我已经添加了图表,但你能详细说明一下series.points中的值吗?因为我有点跟不上你的思路了。 - CatNamedKat
1个回答

17

这是一个代码示例,展示如何创建饼图。希望这能帮到你:

private void DrawPieChart(int value1, int value2, int value3, int value4, int value5)
{
    //reset your chart series and legends
    chart1.Series.Clear();
    chart1.Legends.Clear();

    //Add a new Legend(if needed) and do some formating
    chart1.Legends.Add("MyLegend");
    chart1.Legends[0].LegendStyle = LegendStyle.Table;
    chart1.Legends[0].Docking = Docking.Bottom;
    chart1.Legends[0].Alignment = StringAlignment.Center;
    chart1.Legends[0].Title = "MyTitle";
    chart1.Legends[0].BorderColor = Color.Black;

    //Add a new chart-series
    string seriesname = "MySeriesName";
    chart1.Series.Add(seriesname);
    //set the chart-type to "Pie"
    chart1.Series[seriesname].ChartType = SeriesChartType.Pie;

    //Add some datapoints so the series. in this case you can pass the values to this method
    chart1.Series[seriesname].Points.AddXY("MyPointName", value1);
    chart1.Series[seriesname].Points.AddXY("MyPointName1", value2);
    chart1.Series[seriesname].Points.AddXY("MyPointName2", value3);
    chart1.Series[seriesname].Points.AddXY("MyPointName3", value4);
    chart1.Series[seriesname].Points.AddXY("MyPointName4", value5);
}

我已经尝试在结尾处添加 chart1.SaveImage("sample.png", System.Drawing.Imaging.ImageFormat.Png)。但是 sample.png 文件只是一个空白的白屏,有人能否请指正一下原因? - zeal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接