在.NET中之前常常用GDI去繪製,雖然效果也不錯,自從.NET 4.0開始,專門爲繪製圖表而生的Chart控件出現了,有了它,就能夠輕鬆的繪製你所須要的曲線圖、柱狀圖什麼的了。ide
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; using System.Drawing; namespace DrawGraph { /// <summary> /// 繪製曲線類 /// </summary> public static class DrawClass { #region 繪製曲線函數 /// <summary> /// 繪製曲線函數 /// </summary> /// <param name="listX">X值集合</param> /// <param name="listY">Y值集合</param> /// <param name="chart">Chart控件</param> public static void DrawSpline(List<int> listX, List<double> listY, Chart chart) { try { //X、Y值成員 chart.Series[0].Points.DataBindXY(listX, listY); chart.Series[0].Points.DataBindY(listY); //點顏色 chart.Series[0].MarkerColor = Color.Green; //圖表類型 設置爲樣條圖曲線 chart.Series[0].ChartType = SeriesChartType.Spline; //設置點的大小 chart.Series[0].MarkerSize = 5; //設置曲線的顏色 chart.Series[0].Color = Color.Orange; //設置曲線寬度 chart.Series[0].BorderWidth = 2; //chart.Series[0].CustomProperties = "PointWidth=4"; //設置是否顯示座標標註 chart.Series[0].IsValueShownAsLabel = false; //設置遊標 chart.ChartAreas[0].CursorX.IsUserEnabled = true; chart.ChartAreas[0].CursorX.AutoScroll = true; chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true; //設置X軸是否能夠縮放 chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true; //將滾動條放到圖表外 chart.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = false; // 設置滾動條的大小 chart.ChartAreas[0].AxisX.ScrollBar.Size = 15; // 設置滾動條的按鈕的風格,下面代碼是將全部滾動條上的按鈕都顯示出來 chart.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.All; chart.ChartAreas[0].AxisX.ScrollBar.ButtonColor = Color.SkyBlue; // 設置自動放大與縮小的最小量 chart.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = double.NaN; chart.ChartAreas[0].AxisX.ScaleView.SmallScrollMinSize = 1; //設置刻度間隔 chart.ChartAreas[0].AxisX.Interval = 10; //將X軸上格網取消 chart.ChartAreas[0].AxisX.MajorGrid.Enabled = false; //X軸、Y軸標題 chart.ChartAreas[0].AxisX.Title = "環號"; chart.ChartAreas[0].AxisY.Title = "直徑"; //設置Y軸範圍 能夠根據實際狀況從新修改 double max = listY[0]; double min = listY[0]; foreach (var yValue in listY) { if (max < yValue) { max = yValue; } if (min > yValue) { min = yValue; } } chart.ChartAreas[0].AxisY.Maximum = max; chart.ChartAreas[0].AxisY.Minimum = min; chart.ChartAreas[0].AxisY.Interval = (max - min) / 10; //綁定數據源 chart.DataBind(); } catch (Exception exc) { MessageBox.Show(exc.ToString()); } } #endregion #region 鼠標點擊,經過環號顯示遊標,並縮放到響應位置 /// <summary> /// 鼠標點擊,經過環號顯示遊標,並縮放到響應位置函數 /// </summary> /// <param name="ringNum">環號</param> /// <param name="chart">Chart控件</param> public static void ShowCurByClick(int ringNum, Chart chart) { //設置遊標位置 chart.ChartAreas[0].CursorX.Position = ringNum; //設置視圖縮放 chart.ChartAreas[0].AxisX.ScaleView.Zoom(ringNum - 1, ringNum + 2); //改變曲線線寬 chart.Series[0].BorderWidth = 3; //改變X軸刻度間隔 chart.ChartAreas[0].AxisX.Interval = 1; } #endregion } }
參考文章
1. 使用.net的Chart控件繪製曲線圖函數