在.NET中以前經常用GDI去繪制,雖然效果也不錯,自從.NET 4.0開始,專門為繪制圖表而生的Chart控件出現了,有了它,就可以輕松的繪制你所需要的曲線圖、柱狀圖什么的了。
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控件繪制曲線圖
