[英]C# draw a moving particle
我對C#極為陌生,我有一個簡單的問題:我應該在黑色背景上繪制一個白色粒子(矩形),然后將其從一個屏幕水平移動到另一個屏幕。 我做到了,但問題是它閃爍太多(即,即使速度很高,它也不平滑,我很容易看到每個動作與另一個動作之間的黑色背景)
t.Interval = 1000 / speed;
t.Tick += new EventHandler(t_Tick);
t.Start();
....
void t_Tick(object sender, EventArgs e)
{
//g.Clear(Color.Black);
g.DrawRectangle(new Pen(Brushes.Black, 20), r); //draw a black rectangle in the old position...20 is the thickness of the pen
r.X += move_x;
g.DrawRectangle(new Pen(Brushes.White, 20), r); //draw a white rectangle in the new position...20 is the thickness of the pen
if (r.X >= 1700) ///this means it reached the end of the screen
t.Stop();
}
我使用g.Clear清除了圖形,但是這也不起作用,因此我在舊位置繪制了一個黑色矩形,然后將其移動到新位置。
任何想法如何消除此閃爍,甚至以另一種方式呢?
嘗試一下...向面板添加一個Panel(panel1):
public partial class Form1 : Form
{
private Rectangle r;
private const int rSize = 50;
private const int move_x = 10;
private System.Windows.Forms.Timer tmr;
public Form1()
{
InitializeComponent();
panel1.BackColor = Color.Black;
r = new Rectangle(0, panel1.Height / 2 - rSize / 2, rSize, rSize);
tmr = new System.Windows.Forms.Timer();
tmr.Interval = 50;
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
panel1.Paint += new PaintEventHandler(panel1_Paint);
}
void tmr_Tick(object sender, EventArgs e)
{
r.X += move_x;
panel1.Refresh();
if (r.X > panel1.Width)
{
tmr.Stop();
MessageBox.Show("Done");
}
}
void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.White, r);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.