Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // This simple control plot a (random) graph changing every 200 milliseconds
- //
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Drawing;
- namespace TestForm
- {
- public class Plot : Control
- {
- static Random rand = new Random(123);
- Queue<double> values;
- Timer timer;
- const int pointsNum = 50;
- public Plot()
- : this(200)
- {
- }
- public Plot(int milliseconds)
- {
- timer = new Timer();
- timer.Interval = milliseconds;
- timer.Tick += new EventHandler(timer_Tick);
- values = new Queue<double>(10);
- // initial values
- for (int i = 0; i < pointsNum; i++)
- values.Enqueue(GetNewRandomValue());
- timer.Start();
- }
- void timer_Tick(object sender, EventArgs e)
- {
- values.Dequeue();
- values.Enqueue(GetNewRandomValue());
- this.Invalidate();
- }
- private double GetNewRandomValue()
- {
- return (int)(rand.NextDouble() * 100) / 200.0;
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- var dx0 = (int)(e.ClipRectangle.Width / 10.0);
- var dy0 = (int)(e.ClipRectangle.Height / 10.0);
- // draw border
- e.Graphics.FillRectangle(Brushes.White, e.ClipRectangle);
- // draw X axis
- e.Graphics.DrawLine(new Pen(Color.Black), dx0, e.ClipRectangle.Height - dy0, e.ClipRectangle.Width - dx0, e.ClipRectangle.Height - dy0);
- // draw Y axis
- e.Graphics.DrawLine(new Pen(Color.Black), dx0, dy0, dx0, e.ClipRectangle.Height - dy0);
- // draw the points
- Point[] points = new Point[values.Count];
- int i = 0;
- foreach (var value in values)
- {
- int x = (int)((e.ClipRectangle.Width - 2 * dx0) * (double)i / values.Count) + dx0;
- int y = (int)((e.ClipRectangle.Height - 2 * dy0) * value) + dy0;
- points[i] = new Point(x, y);
- i++;
- }
- e.Graphics.DrawLines(new Pen(Color.Red), points);
- base.OnPaint(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment