C#动态绘制多条曲线
weixin_46896829 人气:0实时绘制多条曲线,纵轴为数值,横轴为时间,精确到毫秒
实现效果如下:
代码:
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 chartTest { public partial class Form1 : Form { private int maxSize=20; //图表显示的数据最大数量 private Queue<string> getX = new Queue<string>(); //存储x坐标 private Queue<Int32> getY = new Queue<int>(); //存储y坐标 System.Timers.Timer timer1 = new System.Timers.Timer(); public Form1() { InitializeComponent(); } //获取时间轴横坐标 private string setX() { string time = DateTime.Now.ToString("mm:ss.fff"); /* if (getX.Count > 15) { getX.Dequeue(); } else { getX.Enqueue(time); }*/ return time; } //获取值 纵坐标 private int setY1() { int y = new Random().Next(-100, 0); /* if (getY.Count > 15) { getY.Dequeue(); } else { getY.Enqueue(y); }*/ return y; } private int setY2() { int y = new Random().Next(-200, 100); /* if (getY.Count > 15) { getY.Dequeue(); } else { getY.Enqueue(y); }*/ return y; } private int setY3() { int y = new Random().Next(100, 300); /* if (getY.Count > 15) { getY.Dequeue(); } else { getY.Enqueue(y); }*/ return y; } private double setY4() { double y0 = new Random().Next(100, 300); double y = y0 * 0.1; /* if (getY.Count > 15) { getY.Dequeue(); } else { getY.Enqueue(y); }*/ return y; } //将坐标点添加进系列进行绘图 private void paint() { try { //series1 if (chart1.Series[0].Points.Count > maxSize) { chart1.Series[0].Points.RemoveAt(0); chart1.Series[0].Points.AddXY(setX(), setY1()); } else { chart1.Series[0].Points.AddXY(setX(), setY1()); } //series2 if (chart1.Series[1].Points.Count > maxSize) { chart1.Series[1].Points.RemoveAt(0); chart1.Series[1].Points.AddXY(setX(), setY2()); } else { chart1.Series[1].Points.AddXY(setX(), setY2()); } //series3 if (chart1.Series[2].Points.Count > maxSize) { chart1.Series[2].Points.RemoveAt(0); chart1.Series[2].Points.AddXY(setX(), setY3()); } else { chart1.Series[2].Points.AddXY(setX(), setY3()); } //series4 if (chart1.Series[3].Points.Count > maxSize) { chart1.Series[3].Points.RemoveAt(0); chart1.Series[3].Points.AddXY(setX(), setY4()); } else { chart1.Series[3].Points.AddXY(setX(), setY4()); } } catch { } } private void timer2_Tick(object sender, EventArgs e) { setX(); setY1(); setY2(); setY3(); setY4(); paint(); //调用画图方法,显示动态折线图 } private void btn_start_Click(object sender, EventArgs e) { if (btn_start.Text.Equals("开始")) { btn_start.Text = "停止"; timer2.Enabled = true; } else { btn_start.Text = "开始"; timer2.Enabled = false; } } } }
加载全部内容