关于Chart控件 C# 自定义

发布时间 2023-12-20 19:20:41作者: x欣x

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;

namespace PieChartLibrary
{
public class ViewProp
{
public Color[] SliceColors = null; // 饼图分片颜色
}

public class DataViewer
{
#region Data

public Dictionary<string, int> DataPoints = null; // 数据点列表
public ViewProp ViewProperty = null; // 绘图属性

#endregion
}

public class DrawPie
{
public List<DataViewer> DataList = null;

public void DrawPies(Chart chart)
{
if (DataList == null)
return;

// 创建和配置图例
Legend legend = new Legend();
legend.Docking = Docking.Bottom;
legend.Alignment = StringAlignment.Center;

foreach (DataViewer dataViewer in DataList)
{
// 创建新的数据系列
Series series = new Series();
series.ChartType = SeriesChartType.Pie;

// 设置饼图分片颜色并添加数据点
if (dataViewer.ViewProperty != null && dataViewer.ViewProperty.SliceColors != null)
{
List<Color> sliceColors = new List<Color>(dataViewer.ViewProperty.SliceColors);
int colorIndex = 0;

foreach (KeyValuePair<string, int> dataPoint in dataViewer.DataPoints)
{
// 创建数据点
DataPoint point = new DataPoint();
point.AxisLabel = dataPoint.Key; // 使用键作为标签
point.SetValueY(dataPoint.Value); // 使用值作为 Y 值

// 设置数据点颜色
if (colorIndex < sliceColors.Count)
{
point.Color = sliceColors[colorIndex]; // 设置数据点的颜色
colorIndex++;
}
// 设置饼图标签样式和线条颜色
series["PieLabelStyle"] = "Outside";
series["PieLineColor"] = "Black";
// 设置数据系列的标签格式为标签文本和百分比
series.Label = "#PERCENT{P0}";
series.Points.Add(point); // 添加数据点
}
}
series.Palette = ChartColorPalette.None;
series.IsVisibleInLegend = true; // 将数据系列显示在图例中

chart.Series.Add(series);// 添加数据系列

}

// 将图例添加到 Chart 控件上
chart.Legends.Add(legend);

}
}

 

----------------------------------------------------------------------------------------------------------------------------------------------------------