简体   繁体   English

C#绘制运动粒子

[英]C# draw a moving particle

I am extremely new to c# and I have a simple question: I am supposed to draw a white particle (rectangle) on a black background and move it horizontally from one of the screen to another. 我对C#极为陌生,我有一个简单的问题:我应该在黑色背景上绘制一个白色粒子(矩形),然后将其从一个屏幕水平移动到另一个屏幕。 I did it but the problem is it blinks too much (ie it is not smooth even when the speed is high, I can easily see the black background between each move and another) 我做到了,但问题是它闪烁太多(即,即使速度很高,它也不平滑,我很容易看到每个动作与另一个动作之间的黑色背景)

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();
        }

I used g.Clear to clear the graphics but this also did not work, so I drew a black rectangle in the old position before moving it to the new position. 我使用g.Clear清除了图形,但是这也不起作用,因此我在旧位置绘制了一个黑色矩形,然后将其移动到新位置。

Any Idea how to remove this blinking or even do it in another way? 任何想法如何消除此闪烁,甚至以另一种方式呢?

Try this out...add a Panel (panel1) to a form: 尝试一下...向面板添加一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM