简体   繁体   中英

How to avoid flickering of graphic object when drawn on picture box in C#?

I am not good at graphic plotting in C#. I am trying to do an animated plotting of a rectangular point on an Image in PictureBox. However, I am facing some flickering issues, I couldn't find the way; how to resolve this issue.

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

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

I have studied from other forums that this issue can be resolved using Timer instead of Thread sleep but don't know how to do it.

Draw what you want in Image of PictureBox, not on PictureBox control:

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

EDIT

if you want to draw on PictureBox control without flickering, put your drawing on pictureBox1.Paint event as follow:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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