c#绘制移动的粒子

本文关键字:粒子 移动 绘制 | 更新日期: 2023-09-27 18:12:53

我对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来清除图形,但这也不起作用,所以我在旧位置画了一个黑色矩形,然后将其移动到新位置。

有任何想法如何删除这个闪烁,甚至用另一种方式吗?

c#绘制移动的粒子

试试这个…添加面板(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);
    }
}