实时曲线绘制

实时绘制时将图直接绘制到控件上,不要通过替换图片来实现,否则会有抖动

解决方法:

当然是在表单上拖置一个pictureBox控件,这里暂且name = pictureBox1

重载OnPaint方法:protectedoverride void OnPaint(PaintEventArgs e)

设置定时器timer, name =timer1, 响应timer1_Tick(),并在事件中重绘pictureBox

 [也可以用Threading来sleep方法来定时]

    pictureBox1.Invalidate();

4 [关键]在OnPaint()方法中绘制

5 [关键]将 pictureBox的设置为透明。属性->>backcolor->>web->>Transparent

完整代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace realtime_demo
{
    public partial class Form1 : Form
    {
        Color backColor = Color.Black;//指定绘制曲线图的背景色  
        private Point[] pointList;//用来绘制曲线图的关键点,依次将这些点连接起来即得到曲线图  
        private Random random = new Random();//用于生成随机数 

        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Point tempPoint;
            base.OnPaint(e);
            //注意,这里千万不可用Graphics g = this.CreateGraphics() 获得绘图变量。否则闪烁将非常厉害。
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias; //
            g.SmoothingMode = SmoothingMode.HighQuality;//绘图模式默认为粗糙模式,将会出现锯齿!

            pointList = new Point[pictureBox1.Width];
           
            //初始化曲线上的所有点坐标  
            for (int i = 0; i < pictureBox1.Width; i++)
            {

                tempPoint = new Point();
                //曲线的横坐标沿x轴依次递增,在横向位置上每个像素都有一个点  
                tempPoint.X = i;
                //曲线上每个点的纵坐标随机生成,但保证在显示区域之内  
                tempPoint.Y = random.Next() % pictureBox1.Height;
                pointList[i] = tempPoint;
            }

            Point p;
            //将当前定位曲线图的坐标点前移,并且将横坐标减1,  
            //这样做的效果相当于移除当前第一个点  
            for (int i = 0; i < pictureBox1.Width - 1; i++)
            {
                p = pointList[i + 1];
                pointList[i] = new Point(p.X - 1, p.Y);
            }
            tempPoint = new Point();
            //新生成曲线图定位点的最后一个点的坐标  
            tempPoint.X = pictureBox1.Width;
            //曲线上每个点的纵坐标随机生成,但保证在显示区域之内  
            tempPoint.Y = random.Next(DateTime.Now.Millisecond) % pictureBox1.Height;
            //在最后再添加一个新坐标点  
            pointList[pictureBox1.Width - 1] = tempPoint;

            g.Clear(backColor);
            //绘制曲线图  
            g.DrawLines(new Pen(Color.Blue), pointList);
            g.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
            timer1.Interval = 1000;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Invalidate();//只重新绘制pictureBox  
        }


    }
}
结果图:
实时曲线绘制_第1张图片


参考文章:http://www.cnblogs.com/hocylan/archive/2008/01/03/1024753.html

你可能感兴趣的:(实时曲线绘制)