用C#实现实时动态图表

工业控制中,经常需要显示实时数据的图表。

下面的Demo演示随时间变化的正弦曲线。

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;
using System.Windows.Forms.DataVisualization.Charting;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;

namespace ChartTest
{
    public partial class Form1 : Form
    {
        private int time = 0;
        public Form1()
        {
            InitializeComponent();
            InitializeChart();

            // 设置定时器
            timer1.Interval = 1000; // 1秒
            timer1.Tick += Timer1_Tick;
            timer1.Start();
        }

        private void InitializeChart()
        {
            // 配置图表区域
            ChartArea chartArea = new ChartArea();
            chart1.ChartAreas.Add(chartArea);

            // 初始化样条曲线
            Series splineSeries = new Series("Spline");
            splineSeries.ChartType = SeriesChartType.Spline;
            chart1.Series.Add(splineSeries);

            // 初始化水平线
            Series horizontalLineSeries = new Series("HorizontalLine");
            horizontalLineSeries.ChartType = SeriesChartType.Line;
            horizontalLineSeries.Points.AddXY(0, 1.5);
            horizontalLineSeries.Points.AddXY(4, 1.5);
            horizontalLineSeries.BorderDashStyle = ChartDashStyle.Dash;
            chart1.Series.Add(horizontalLineSeries);
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            // 每秒更新样条曲线的点
            UpdateSplineSeries();

            time++;
        }

        private void UpdateSplineSeries()
        {
            var splineSeries = chart1.Series["Spline"];
            splineSeries.Points.Clear();

            int startPoint = time > 10 ? time - 10 : 0;
            for (int i = startPoint; i <= time; i++)
            {
                splineSeries.Points.AddXY(i, Math.Sin(i * 0.5));
            }

            var lineSeries = chart1.Series["HorizontalLine"];
            lineSeries.Points.Clear();
            for (int i = startPoint; i <= time; i++)
            {
                lineSeries.Points.AddXY(i, 1.5);
            }

            // 调整图表区域以适应新的数据点
            chart1.ChartAreas[0].RecalculateAxesScale();

            // 动态调整x轴范围
            var xAxis = chart1.ChartAreas[0].AxisX;
            xAxis.Minimum = startPoint;
            xAxis.Maximum = time;
        }

    }
}

你可能感兴趣的:(自动化,c#,开发语言)