首頁 > 軟體

C#使用DevExpress中的XtraCharts控制元件實現圖表

2022-05-27 14:03:45

一、總體概述

官方檔案:

https://docs.devexpress.com/WindowsForms/8117/controls-and-libraries/chart-control

ChartControl控制元件主要包括Chart Title、Legend、Annotations、Diagram、Series五部分;如圖:

二、chartControl層XYDiagram層

chartControl像DEV的其它控制元件一樣,這一層之相當於是一個殼子,我們平時在這裡面設定的屬性也不多。而且都是些常規屬性,比如大小、停靠方式等等。

XYDiagram這一層就比較關鍵了,主要是涉及到XY軸的顯示方式和卷軸顯示等。並且座標軸的顯示方式和資料型別也有很大的關係,主要包括3種型別,資料型別是根據新增到Series中的資料型別決定的,主要屬性是ArgumentScaleType。所以涉及到3種不同的設定方式。

1.當座標軸的資料型別是數位時

2. 當前資料型別是字串時

其它設定同上,主要是要想出現卷軸,在設計面板中還不能實現,必須通過程式碼設定

DevExpress.XtraCharts.XYDiagram xyDiagram1 = (XYDiagram)this.chartControl1.Diagram;          
xyDiagram1.AxisX.Range.MaxValueInternal = 3; //這個屬性在設計檢視裡面是看不到的,只有程式碼裡面才可以設定。
xyDiagram1.AxisX.Range.MinValueInternal = -0.5D;

3.當前資料型別是時間

AxisX ax = (XYDiagram)chartControl1.Diagram;
ax.GridSpacingAuto = false;
ax.DateTimeMeasureUnit = DateTimeMeasurementUnit.Minute;//這個可以根據你自己的情況設定
ax.DateTimeGridAlignment = DateTimeMeasurementUnit.Second; //這個是間隔單位
ax.GridSpacing = 10; // 每10秒為一個間隔。

三、範例

1.餅狀圖

1.1、新增ChartControl控制元件

在工具箱中找到ChartControl控制元件,拖到視窗中,建立Pie;

1.2、準備資料

private DataTable CreateChartData()
 {
     DataTable dtData = SqlHelper.GetDataSet(sql, parameters).Tables[0];
     DataTable table = new DataTable("Table1");
     table.Columns.Add("Name", typeof(String));
     table.Columns.Add("Value", typeof(Double));
     foreach (DataRow item in dtData.Rows)
     {
         var array = new object[] { item["value_num"], item["count"] };
         table.Rows.Add(array);
     }
     return table;
 }

資料可以自定義,返回型別為DataTable即可。

1.3、根據資料建立餅狀圖

/// <summary>
/// 根據資料建立一個餅狀圖
/// </summary>
/// <returns></returns>
private void BuilderDevChart()
{
    //清空ChartControl控制元件
    chartControl1.Series.Clear();
    Series _pieSeries = new Series("學生成績餅狀圖", ViewType.Pie);
    _pieSeries.ArgumentDataMember = "Name";  //繫結圖表的橫座標  
    _pieSeries.ValueDataMembers[0] = "Value";  //繫結圖表的縱座標座標
    _pieSeries.DataSource = CreateChartData(CourseID);
    chartControl1.Series.Add(_pieSeries);
    chartControl1.AddTitle("學生成績餅狀圖");
    _pieSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues;
    ChartUtils.SetPieNumber(_pieSeries);
}

1.4、設定餅狀Series顯示方式(值/百分比)

/// <summary>
/// 餅狀Series設定成百分比顯示
/// </summary>
/// <param name="series">Series</param>
public static void SetPiePercentage(this Series series)
{
    if (series.View is PieSeriesView)
    {
        ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = true;
        ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Percent;
        ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0;
    }
}

/// <summary>
/// 餅狀Series設定顯示格式,是以數位還是百分號顯示
/// </summary>
/// <param name="series">Series</param>
public static void SetPieNumber(Series series)
{
    if (series.View is PieSeriesView)
    {
        //設定為值
        ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = false;
        ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Number;
        ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0;
    }
}

實現結果:

2.柱狀圖

2.1、新增ChartControl控制元件

在工具箱中找到ChartControl控制元件,拖到視窗中,建立Bar:

2.2、準備資料

/// <summary>
/// 建立資料
/// </summary>
/// <returns></returns>
private DataTable CreateBarData()
{
    string sql = string.Format(@"
                             SELECT c.CollegeName,COUNT(*)
                                     FROM studentmanager.student 
                                     LEFT JOIN college AS c ON c.CollegeID=student.CollegeID
                                     GROUP BY c.CollegeID");
    DataSet ds = _db.GetResult(sql);
    if (ds != null)
    {
        DataTable dtData = ds.Tables[0];
        DataTable table = new DataTable("Table1");
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Value", typeof(int));
        foreach (DataRow item in dtData.Rows)
        {
            var array = new object[] { item["CollegeName"], item["COUNT(*)"] };
            table.Rows.Add(array);
        }
        return table;
    }
    else
    {
        return null;
    }
}

資料可以自定義,返回型別為DataTable即可。

2.3、根據資料建立柱狀圖

private void BuilderDevBarChart()
{
    chartControl2.Series.Clear();
    Series _barSeries = new Series("", ViewType.Bar);
    _barSeries.ArgumentDataMember = "Name";//x軸
    _barSeries.ValueDataMembers[0] = "Value";//Y軸
    _barSeries.DataSource = CreateBarData();
    _barSeries.SetColorEach(true);
    chartControl2.Series.Add(_barSeries);

    _barSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues;

    chartControl2.SetXLableAngle(-35);
    chartControl2.SetCrosshair(true);

    chartControl2.Legend.Direction = LegendDirection.LeftToRight;
    chartControl2.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
    chartControl2.Legend.AlignmentVertical = LegendAlignmentVertical.BottomOutside;
    chartControl2.AddTitle("學院學生數量柱狀圖");
}

2.4、用到的方法

public static class ChartUtils
{
    /// <summary>
    /// 增加資料篩選
    /// </summary>
    /// <param name="SeriesBase">Series</param>
    /// <param name="columnName">列名稱</param>
    /// <param name="value">列名稱對應的篩選數值</param>
    /// <param name="dataFilterCondition">DataFilterCondition列舉</param>
    public static void AddDataFilter(this SeriesBase series, string columnName, object value, DataFilterCondition dataFilterCondition)
    {
        series.DataFilters.Add(new DataFilter(columnName, value.GetType().FullName, dataFilterCondition, value));
    }

    /// <summary>
    /// 設定X軸Lable角度
    /// </summary>
    /// <param name="chart">ChartControl</param>
    /// <param name="angle">角度</param>
    public static void SetXLableAngle(this ChartControl chart, int angle)
    {
        XYDiagram _xyDiagram = (XYDiagram)chart.Diagram;
        if (_xyDiagram != null)
            _xyDiagram.AxisX.Label.Angle = angle;
    }
    /// <summary>
    ///  設定Y軸Lable角度
    /// </summary>
    /// <param name="chart">ChartControl</param>
    /// <param name="angle">角度</param>
    public static void SetYLableAngle(this ChartControl chart, int angle)
    {
        XYDiagram _xyDiagram = (XYDiagram)chart.Diagram;
        _xyDiagram.AxisY.Label.Angle = angle;
    }

    /// <summary>
    /// 設定ColorEach
    /// </summary>
    /// <param name="chart">ChartControl</param>
    /// <param name="colorEach">是否設定成ColorEach</param>
    public static void SetColorEach(this Series series, bool colorEach)
    {
        SeriesViewColorEachSupportBase colorEachView = (SeriesViewColorEachSupportBase)series.View;
        if (colorEachView != null)
        {
            colorEachView.ColorEach = colorEach;
        }
    }

    /// <summary>
    /// 設定是否顯示十字標線
    /// </summary>
    /// <param name="chart">ChartControl</param>
    /// <param name="crosshair">是否顯示十字標線</param>
    public static void SetCrosshair(this ChartControl chart, bool crosshair)
    {
        chart.CrosshairEnabled = crosshair ? DefaultBoolean.True : DefaultBoolean.False;
        chart.CrosshairOptions.ShowArgumentLabels = crosshair;
        chart.CrosshairOptions.ShowArgumentLine = crosshair;
        chart.CrosshairOptions.ShowValueLabels = crosshair;
        chart.CrosshairOptions.ShowValueLine = crosshair;
    }

    /// <summary>
    /// 新增ChartControl的Title文字
    /// </summary>
    /// <param name="chart">ChartControl</param>
    /// <param name="title">Title文字</param>
    public static void AddTitle(this ChartControl chart, string title)
    {
        chart.Titles.Clear();  //先清除以前的標題
        ChartTitle _title = new ChartTitle();
        _title.Text = title;
        chart.Titles.Add(_title);
    }

    /// <summary>
    /// 餅狀Series設定成百分比顯示
    /// </summary>
    /// <param name="series">Series</param>
    public static void SetPiePercentage(this Series series)
    {
        if (series.View is PieSeriesView)
        {
            ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = true;
            ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Percent;
            ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0;
        }
    }

    /// <summary>
    /// 餅狀Series設定顯示格式,是以數位還是百分號顯示
    /// </summary>
    /// <param name="series">Series</param>
    public static void SetPieNumber(Series series)
    {
        if (series.View is PieSeriesView)
        {
            //設定為值
            ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = false;
            ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Number;
            ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0;
        }
    }

    /// <summary>
    /// ChartControl設定標題
    /// </summary>
    /// <param name="chartControl"></param>
    /// <param name="HTitle"></param>
    public static void SetHZTitle(ref ChartControl chartControl, string HTitle)
    {
        chartControl.Titles.Clear();                    //先清除以前的標題

        //橫標題設定
        ChartTitle titles = new ChartTitle();            //宣告標題

        titles.Text = HTitle;                            //名稱
        titles.TextColor = System.Drawing.Color.Black;   //顏色
        titles.Indent = 5;                                //設定距離  值越小柱狀圖就越大
        titles.Font = new Font("Tahoma", 14, FontStyle.Bold);            //設定字型
        titles.Dock = ChartTitleDockStyle.Top;           //設定對齊方式
        titles.Alignment = StringAlignment.Center;       //居中對齊
        chartControl.Titles.Add(titles);                 //新增標題                    
    }
}

實現結果:

四、事件

1、CustomDrawAxisLabel : 接管此事件來獲得軸標籤。客製化軸標籤

private void chartControl1_CustomDrawAxisLabel(object sender, CustomDrawAxisLabelEventArgs e)
{
    AxisBase axis = e.Item.Axis;
    if (axis is AxisY || axis is AxisY3D || axis is RadarAxisY)
    {
        double axisValue = (double)e.Item.AxisValue;
        if (axisValue < 0)
        {
            e.Item.TextColor = Color.Red;
        }
        else if (axisValue > 0)
        {
            e.Item.Text = "+" + e.Item.Text;
            e.Item.TextColor = Color.Green;
        }
        else if (axisValue == 0)
        {
            e.Item.Text = "Zero";
        }
    }
}

2、ObjectHotTracked:滑鼠指標懸停位置

private void chartControl1_ObjectHotTracked(object sender, HotTrackEventArgs e)
{
    if (e.AdditionalObject is AxisTitle)
    {
        MessageBox.Show(e.AdditionalObject.GetType().ToString());
    }
}

3、CustomDrawSeries :自定義繪製系列

private void chartControl1_CustomDrawSeries(object sender, CustomDrawSeriesEventArgs e)
{
    // Find all Bar Series by their view type,and fill them with Aqua color.
    if (e.Series.View is BarSeriesView)
        e.SeriesDrawOptions.Color = Color.Aqua;

    // Find the series by its name,  and change its line style to dash-dot-dot. (Here it's assumed that the series view type is LineSeriesView).
    if (e.Series.Name == "Line Series")
        ((LineDrawOptions)e.SeriesDrawOptions).LineStyle.DashStyle = DevExpress.XtraCharts.DashStyle.DashDotDot;

    // Find all Point Series by the type of its DrawOptions, and change their marker kind to diamond.
    if (e.SeriesDrawOptions.GetType() == typeof(PointDrawOptions))
        ((PointDrawOptions)e.SeriesDrawOptions).Marker.Kind =
        MarkerKind.Diamond;
}

4、CustomDrawSeriesPoint:自定義繪製系列點

private void chartControl1_CustomDrawSeriesPoint(object sender, CustomDrawSeriesPointEventArgs e)
{
    // These changes will be applied to Bar Series only.
    BarDrawOptions drawOptions = e.SeriesDrawOptions as BarDrawOptions;
    if (drawOptions == null)
        return;

    // Get the fill options for the series point.
    drawOptions.FillStyle.FillMode = DevExpress.XtraCharts.FillMode.Gradient;
    RectangleGradientFillOptions options = drawOptions.FillStyle.Options as RectangleGradientFillOptions;
    if (options == null)
        return;

    // Get the value at the current series point.
    double val = e.SeriesPoint[0];
    // If the value is less than 1, hide the point's label.
    if (e.SeriesPoint[0] < 1)
    {
        e.LabelText = "";
    }
    // If the value is less than 2.5, then fill the bar with green colors.
    if (val < 2.5)
    {
        options.Color2 = Color.FromArgb(154, 196, 84);
        drawOptions.Color = Color.FromArgb(81, 137, 3);
        drawOptions.Border.Color = Color.FromArgb(100, 39, 91, 1);
    }
    // ... if the value is less than 5.5, then fill the bar with yellow colors.
    else if (val < 5.5)
    {
        options.Color2 = Color.FromArgb(254, 233, 124);
        drawOptions.Color = Color.FromArgb(249, 170, 15);
        drawOptions.Border.Color = Color.FromArgb(60, 165, 73, 5);
    }
    // ... if the value is greater, then fill the bar with red colors.
    else
    {
        options.Color2 = Color.FromArgb(242, 143, 112);
        drawOptions.Color = Color.FromArgb(199, 57, 12);
        drawOptions.Border.Color = Color.FromArgb(100, 155, 26, 0);
    }
}

五、匯出

1、匯出為PDF:

圖表會被自動拆分,

if (chartControlidx.IsPrintingAvailable) //是否能被列印或輸出
   {
     // Exports to a PDF file.
     chartControlidx.ExportToPdf(path);
     // Exports to a stream as PDF.
     System.IO.FileStream pdfStream = new System.IO.FileStream(path, System.IO.FileMode.Create);
     chartControlidx.ExportToPdf(pdfStream);
      //...
      pdfStream.Close();
    }

2、匯出為影象檔案:

if (chartControlidx.IsPrintingAvailable) //是否能被列印或輸出
  {
    // Create an image in the specified format from the chart and save it to the specified path.
    chartControlidx.ExportToImage(path, System.Drawing.Imaging.ImageFormat.Png);   //png格式
  }

六、參考

WinForm使用DecExpress控制元件中的ChartControl外掛繪製圖表

到此這篇關於C#使用XtraCharts控制元件實現圖表的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com