【问题标题】:How to avoid flickering of graphic object when drawn on picture box in C#?在C#中的图片框上绘制时如何避免图形对象闪烁?
【发布时间】:2018-03-19 15:32:53
【问题描述】:

我不擅长用 C# 绘制图形。我正在尝试对 PictureBox 中的图像上的矩形点进行动画绘图。但是,我面临一些闪烁的问题,我找不到方法;如何解决这个问题。

g = pictureBox1.CreateGraphics();
g.FillRectangle(Brushes.Green, Convert.ToInt32(x), Convert.ToInt32(y), 10, 10);

Thread.Sleep(20);
invalidate_pictureBox1();
update_pictureBox1();    

我在其他论坛上研究过,这个问题可以使用 Timer 而不是 Thread sleep 解决,但不知道该怎么做。

【问题讨论】:

标签: c# graphics picturebox


【解决方案1】:

在 PictureBox 的 Image 中绘制你想要的,而不是在 PictureBox 控件上:

    private void timer1_Tick(object sender, EventArgs e)
    {
        Image img = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(img);
        g.FillRectangle(Brushes.Green, Convert.ToInt32(x), Convert.ToInt32(y), 10, 10);
        pictureBox1.Image = img;
    }

编辑

如果您想在 PictureBox 控件上绘图而不闪烁,请将您的绘图放在pictureBox1.Paint 事件上,如下所示:

    private void Form1_Load(object sender, EventArgs e)
    {
        // Your Solution
        int x = 0, y = 0;
        pictureBox1.Paint += new PaintEventHandler(delegate(object sender2, PaintEventArgs e2)
        {
            e2.Graphics.FillRectangle(Brushes.Green, x, y, 10, 10);
        });

        // Test
        buttonTest1.Click += new EventHandler(delegate(object sender2, EventArgs e2)
        {
            x++;
            pictureBox1.Invalidate();
        });

        buttonTest2.Click += new EventHandler(delegate(object sender2, EventArgs e2)
        {
            for (x = 0; x < pictureBox1.Width - 10; x++)
            {
                System.Threading.Thread.Sleep(50);
                pictureBox1.Invalidate();
                pictureBox1.Refresh();
            }
        });

        buttonTest3.Click += new EventHandler(delegate(object sender2, EventArgs e2)
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Tick += new EventHandler(delegate(object sender3, EventArgs e3)
            {
                if (x <= pictureBox1.Width - 10)
                    x++;
                pictureBox1.Invalidate();
            });
            t.Enabled = true;
            t.Interval = 50;
        });
    }

【讨论】:

  • 感谢您的回复 hussein,但我想知道我应该在哪里调用此计时器事件以将延迟放入我的程序中??
  • OP 声明他希望将动画绘制到控件上,这是可行的方法。但只能通过 Paint 事件及其 e.Graphics 对象。
  • 只要 Timer 处于活动状态,就会在至少 Interval ms 之后重复调用计时器事件。要触发 Paint 事件,您调用 PBox 的 Invalidate ..
  • 谢谢,如果我没有做对,请原谅。尝试编辑版本...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多