如何在c#中画圆和移动
本文关键字:移动 | 更新日期: 2023-09-27 18:23:37
我正试图在c#中画一个圆并以一种形式移动它。我使用GDI绘制,如下所示。假设我有1类Circle
int postitionX, postitionY, radius, angle;
void Draw(Graphics g)
{
g.DrawEllipse(Pen, postitionX, postitionY, radius, radius);
g.FillEllipse(SolidBrush, postitionX, postitionY, radius, radius);
}
并形成主I初始圆(位置X=0,位置Y=10,半径=20,角度=30;)
private void form_Paint(object sender, PaintEventArgs e)
{
<caculation postition next>
mycircle.Draw(e.Graphics)
}
但问题是函数form_Paint多次运行,使圆移出显示。有人能不给我解决方案吗?
Invalidate
将导致表单的完全重新绘制,并将调用"form_Paint"事件处理程序。这将导致一个无休止的循环。(我现在明白了,TaW只是早些时候)。如果你想在你的窗体上设置一个圆圈的动画,你可以使用以下方法:
在表单上设置一个Timer
,将Interval
设置为30,并将Enabled
设置为True。实施Tick
事件:
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
}
现在更新您的form_Paint处理程序:
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
}
通过将timer1.Interval
的valye与您对下一个位置的计算相结合,可以使动画变慢或变快。
所以假设我画了一条通向3个点的圆的路径。如果我使用定时器勾选然后如何。
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
}
因此,圆将穿过点3,然后form_main开始重新绘制。我不想那样。所以,你怎么能不