要使用WinForm繪制實時曲線圖,可以按照以下步驟進(jìn)行操作:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RealTimeChart
{
public partial class Form1 : Form
{
private Random random = new Random();
private Timer timer = new Timer();
public Form1()
{
InitializeComponent();
// 設(shè)置圖表的樣式
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 100;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 100;
chart1.Series.Add("數(shù)據(jù)");
chart1.Series["數(shù)據(jù)"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series["數(shù)據(jù)"].Color = Color.Blue;
// 設(shè)置定時器
timer.Interval = 1000; // 每隔1秒鐘更新一次數(shù)據(jù)
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// 生成隨機(jī)數(shù)據(jù)
double x = random.Next(0, 100);
double y = random.Next(0, 100);
// 添加數(shù)據(jù)到圖表中
chart1.Series["數(shù)據(jù)"].Points.AddXY(x, y);
// 只保留最新的100個數(shù)據(jù)點(diǎn)
if (chart1.Series["數(shù)據(jù)"].Points.Count > 100)
{
chart1.Series["數(shù)據(jù)"].Points.RemoveAt(0);
}
}
}
}
注意:在使用Chart控件前,需要在項目中引用System.Windows.Forms.DataVisualization庫。