Umair Shahid
Umair Shahid

Reputation: 21

Stop flickering when drawing multiple rectangles on picture box

When drawing multiple rectangles in a picture box with the below code, it flickers.
What can I do about it?

private void drawRect(int sx, int sy, int ex, int ey, int w, int h)
{
    Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black));
    //Top ok
    pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, 0, w, sy);
    //Bottom
    pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, ey, w, h);
    //Left ok
    pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
    //Right
    pictureBox1.CreateGraphics().FillRectangle(cloud_brush, ex, sy, w, ey - sy);
}

Upvotes: 0

Views: 205

Answers (1)

Pepernoot
Pepernoot

Reputation: 3609

You are using CreateGraphics() for every paint action but you only have to create it once. CreateGraphics() is slow so this will speed up your code a lot.

    private void drawRect(int sx, int sy, int ex, int ey, int w, int h)
    {
        using (Graphics g = CreateGraphics())
        using (Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black)))
        {
            //Top ok
            g.FillRectangle(cloud_brush, 0, 0, w, sy);
            //Bottom
            g.FillRectangle(cloud_brush, 0, ey, w, h);
            //Left ok
            g.FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
            //Right
            g.FillRectangle(cloud_brush, ex, sy, w, ey - sy);
        }
    }

The reason it flickers is the use of CreateGraphics. I recommend you to use the paint event instead.

    private void drawRect(Graphics g, int sx, int sy, int ex, int ey, int w, int h)
    {
        using (Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black)))
        {
            //Top ok
            g.FillRectangle(cloud_brush, 0, 0, w, sy);
            //Bottom
            g.FillRectangle(cloud_brush, 0, ey, w, h);
            //Left ok
            g.FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
            //Right
            g.FillRectangle(cloud_brush, ex, sy, w, ey - sy);
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        drawRect(e.Graphics,80, 190, 160, 140, 100, 130);
    }

Upvotes: 1

Related Questions