C#绘制采用数据曲线图
时间:2011-03-16 来源:c#小菜
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<byte> 数据采样= new List<byte>();
private int 网格偏移= 0;
private Random 随机数= new Random();
private const int 网格大小= 12;
private Pen 网格颜色= new Pen(Color.FromArgb(0x00, 0x80, 0x40));
private Pen 曲线颜色= new Pen(Color.FromArgb(0x00, 0xFF, 0x00));
private void timer1_Tick(object sender, EventArgs e)
{
while (数据采样.Count > 1000) 数据采样.RemoveAt(0);
数据采样.Add((byte)随机数.Next(256));
网格偏移= (网格偏移+ 1) % 网格大小;
Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Black, e.Graphics.ClipBounds);
#region 绘制网格
for (int i = ClientSize.Width - 网格偏移; i >= 0; i -= 网格大小)
e.Graphics.DrawLine(网格颜色, i, 0, i, ClientSize.Height);
for (int i = ClientSize.Height; i >= 0; i -= 网格大小)
e.Graphics.DrawLine(网格颜色, 0, i, ClientSize.Width, i);
#endregion
#region 绘制曲线
if (数据采样.Count <= 1) return; // 一个数据就不绘制了
byte A = 数据采样[数据采样.Count - 1];
for (int i = 数据采样.Count - 2; i >= 0; i--)
{
byte B = 数据采样[i];
e.Graphics.DrawLine(曲线颜色,
new Point(ClientSize.Width - 数据采样.Count + i - 1,
(int)(((double)A / 255) * ClientSize.Height)),
new Point(ClientSize.Width - 数据采样.Count + i,
(int)(((double)B / 255) * ClientSize.Height)));
A = B;
}
#endregion
}
private void Form1_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void Form1_Load(object sender, EventArgs e)
{
DoubleBuffered = true;
timer1.Enabled = true;
timer1.Interval = 100;
}
}
}