本文实例为大家分享了C#动态绘制多条曲线的具体代码,供大家参考,具体内容如下
实时绘制多条曲线,纵轴为数值,横轴为时间,精确到毫秒
实现效果如下:
代码:
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");
return time;
}
//获取值 纵坐标
private int setY1()
{
int y = new Random().Next(-100, 0);
return y;
}
private int setY2()
{
int y = new Random().Next(-200, 100);
return y;
}
private int setY3()
{
int y = new Random().Next(100, 300);
return y;
}
private double setY4()
{
double y0 = new Random().Next(100, 300);
double y = y0 * 0.1;
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;
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。