Reputation: 21
I'm trying to draw one circle and move it in one form in c #. I use GDI to draw, as follows. Suppose that I have 1 class Circle
int postitionX, postitionY, radius, angle;
void Draw(Graphics g)
{
g.DrawEllipse(Pen, postitionX, postitionY, radius, radius);
g.FillEllipse(SolidBrush, postitionX, postitionY, radius, radius);
}
and in form main I init circle(postitionX=0, postitionY=10, radius=20, angle=30;)
private void form_Paint(object sender, PaintEventArgs e)
{
<caculation postition next>
mycircle.Draw(e.Graphics)
}
But the problem is that function form_Paint run many times and make circle move out display. Can someone give me no solution?
Upvotes: 2
Views: 7947
Reputation: 1258
Invalidate
will cause a full repaint of your form and will invoke your `form_Paint' event handler. This will cause an endless loop. (I see now TaW was just earlier).
If you want to animate a circle on your form, you could use the following approach:
Put a Timer
on your form, set Interval
on 30 and Enabled
to True. Implement the Tick
event:
private int deltaX = 1;
private int deltaY = 1;
private void timer1_Tick(object sender, EventArgs e)
{
// TO DO your caculation postition, like so:
// be sure window width/height is much larger than 2 * radius:
if ((postitionX - radius) <= 0)
deltaX = 1;
if ((postitionX + radius) >= ClientRectangle.Width)
deltaX = -1;
positionX += deltaX;
if ((postitionY - radius) <= 0)
deltaY = 1;
if ((postitionY + radius) >= ClientRectangle.Heigth)
deltaY = -1;
positionY += deltaY;
// Now you have calculated a 'new animation frame'.
// Now force repaint to draw.
Invalidate(); // This will force a repaint
}
Now update your form_Paint handler:
private void form_Paint(object sender, PaintEventArgs e)
{
// caculation postition next HAS TO BE REMOVED FROM HERE
mycircle.Draw(e.Graphics)
// Invalidate(); HAS TO BE REMOVED FROM HERE
}
By playing with the valye for timer1.Interval
in combination with your calculations of next position, you can make the animation slower or faster.
Upvotes: 3
Reputation: 21
So suppose I draw the path of the circle go to 3 points. if i use timer tick then how.
private void timer1_Tick(object sender, EventArgs e)
{
// Go to point 1
// Go to point 2
// Go to point 3
}
private void form_Paint(object sender, PaintEventArgs e)
{
// caculation postition next HAS TO BE REMOVED FROM HERE
mycircle.Draw(e.Graphics)
// Invalidate(); HAS TO BE REMOVED FROM HERE
}
So the circle will go through point 3 then form_main start redraw.I did not want that. So, how can not you
Upvotes: 0