I need to draw sin(x)/x graphic into PictureBox in animation mode by timer component. I have axes already on my picBox and graphic draws from 0;0. Also I have some code from this forum, but there my graphic draws FROM RIGHT TO THE LEFT, and I need to draw it FROM LEFT TO THE RIGHT. And I need to draw it in animation mode by timer. Could anybody help me?
Here’s my drawing function:
private void drawStream()
{
const int scaleX = 35;
const int scaleY = 35;
Point picBoxTopLeft = new Point(0, 0);
Point picBoxTopLeftm1 = new Point(-1, 0);
int halfX = picBox.Width / 2;
int halfY = picBox.Height / 2;
Size size = new Size(halfX + 20, picBox.Height);
Graphics gr = picBox.CreateGraphics();
gr.TranslateTransform(halfX, halfY);
gr.ScaleTransform(scaleX, scaleY);
gr.ResetClip();
float lastY = (float)Math.Sin(0);
float y = lastY;
Pen p = new Pen(Color.Red, 0.015F);
float stepX = 1F / scaleX;
for (float x = 0; x < 15; x += stepX)
{
gr.CopyFromScreen(picBox.PointToScreen(picBoxTopLeft), picBoxTopLeftm1, size, CopyPixelOperation.SourceCopy);
y = (float)Math.Sin(x);
gr.DrawLine(p, -stepX, lastY, 0, y);
lastY = y;
}
}
Thanx a lot.
P.S. Sorry for my English, I’m Ukrainian.
It looks like the line:
Will always draw a line from (-stepX, lastY) to (0, y). Only the Y coordinates of these points change during your loop which doesn’t look like what you want.
Moreover, you’re stepping in the X direction by
stepXwhich is defined as being 1 / 35.0f. This means you’re stepping 35 times per whole pixel; a bit excessive. Get rid of yourScaleTransformand instead scale your independent variable (x) to get a more sensible frequency. You should probably also increase youramplitudeto get a good looking curve as well.I think your drawing loop should look more like:
This will draw from the origin (0,0) to the right side of the picture box at once. To animate this you’re going to need to take this code and instead of looping all the way to
halfXyou want to loop only part of the way and keep track of where you the next time yourTimerfires it’s event.edit:
Every time you create a
Penobject you take a handle from Windows through GDI. These handles are only returned to be reused when youDispose()thePenobject. If you create a new Pen every time you draw and don’t dispose them you’ll run out of handles eventually!To be safe when using these types of objects (
Pen,Brush,Font, and more need to be disposed) wrap them in ausingstatement: