Guest User

Dynamic plot

a guest
Feb 14th, 2011
3,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. //
  2. // This simple control plot a (random) graph changing every 200 milliseconds
  3. //
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Drawing;
  10.  
  11. namespace TestForm
  12. {
  13. public class Plot : Control
  14. {
  15. static Random rand = new Random(123);
  16.  
  17. Queue<double> values;
  18. Timer timer;
  19.  
  20. const int pointsNum = 50;
  21.  
  22. public Plot()
  23. : this(200)
  24. {
  25. }
  26.  
  27. public Plot(int milliseconds)
  28. {
  29. timer = new Timer();
  30. timer.Interval = milliseconds;
  31.  
  32. timer.Tick += new EventHandler(timer_Tick);
  33.  
  34. values = new Queue<double>(10);
  35.  
  36. // initial values
  37. for (int i = 0; i < pointsNum; i++)
  38. values.Enqueue(GetNewRandomValue());
  39.  
  40. timer.Start();
  41.  
  42. }
  43.  
  44. void timer_Tick(object sender, EventArgs e)
  45. {
  46. values.Dequeue();
  47. values.Enqueue(GetNewRandomValue());
  48.  
  49. this.Invalidate();
  50. }
  51.  
  52. private double GetNewRandomValue()
  53. {
  54. return (int)(rand.NextDouble() * 100) / 200.0;
  55. }
  56.  
  57. protected override void OnPaint(PaintEventArgs e)
  58. {
  59. var dx0 = (int)(e.ClipRectangle.Width / 10.0);
  60. var dy0 = (int)(e.ClipRectangle.Height / 10.0);
  61.  
  62. // draw border
  63. e.Graphics.FillRectangle(Brushes.White, e.ClipRectangle);
  64.  
  65. // draw X axis
  66. e.Graphics.DrawLine(new Pen(Color.Black), dx0, e.ClipRectangle.Height - dy0, e.ClipRectangle.Width - dx0, e.ClipRectangle.Height - dy0);
  67.  
  68. // draw Y axis
  69. e.Graphics.DrawLine(new Pen(Color.Black), dx0, dy0, dx0, e.ClipRectangle.Height - dy0);
  70.  
  71. // draw the points
  72. Point[] points = new Point[values.Count];
  73. int i = 0;
  74. foreach (var value in values)
  75. {
  76. int x = (int)((e.ClipRectangle.Width - 2 * dx0) * (double)i / values.Count) + dx0;
  77. int y = (int)((e.ClipRectangle.Height - 2 * dy0) * value) + dy0;
  78.  
  79. points[i] = new Point(x, y);
  80.  
  81. i++;
  82. }
  83.  
  84. e.Graphics.DrawLines(new Pen(Color.Red), points);
  85.  
  86. base.OnPaint(e);
  87. }
  88.  
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment