MSDN Library

How to: Draw Images Off-Screen

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

You can reduce the flicker when drawing large images by using a Graphics object not associated with the form to create the image off-screen. Then draw the image on the screen using a Graphics object of the form.

This example overrides the OnPaint method to create a large bitmap off-screen using a Graphics object derived from the bitmap. Then it draws the bitmap to the screen using the Graphics object returned from the Graphics property of the PaintEventArgs.

After the form loads, it can take a few seconds for the image to appear.

protected override void OnPaint(PaintEventArgs e)

    Bitmap bmp;
    Graphics gOff;

    // Create a bitmap the size of the form.
    bmp = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);

    SolidBrush BlueBrush = new SolidBrush(Color.Blue);
    Pen WhitePen = new Pen(Color.White,3);

    // Create a Graphics object that is not on the form.
    gOff = Graphics.FromImage(bmp);
    gOff.FillRectangle(new SolidBrush(Color.Red), 0, 0, 
        bmp.Width, bmp.Height);

    // Draw a complex bitmap of 1000 random rectangles. It will take a few
    // seconds to draw.
    for (int z = 1; z <= 1000; z++)
        // Generate a random number with
        // seeds from the system clock.
        Random rx = new Random();
        Random ry = new Random();

        // Create rectangles in the inner area of the form.
        Rectangle rect = new Rectangle(rx.Next(10,200), ry.Next(10,200),
            10, 10);
        gOff.DrawRectangle(WhitePen, rect);
        gOff.FillRectangle(BlueBrush, rect);

    // Use the Graphics object from 
    // PaintEventArgs to draw the bitmap onto the screen.
    e.Graphics.DrawImage(bmp, 0, 0, ClientRectangle, GraphicsUnit.Pixel);

This example requires references to the following namespaces:

Note that the Graphics object created for the off-screen drawing should be disposed. The Graphics object returned by the Graphics property of the PaintEventArgs object is destroyed by the garbage collector and does not need to be explicitly disposed.

© 2016 Microsoft