Software Bpath Network


Double Buffering


Language: C++
Compiler: MS Visual C++ 5.0 SP3
Environment: Windows 9x/NT

What's this?


This example shows how could be useful 'Double Buffering' technique.

How does it work?


Download source code (14 kb)

If you try to draw directly into a specific device context repeatedly, you will obtain a boring effect: flickers. To eliminate this effect there is an useful method called 'Double Buffering'.
This trick uses a memory device context used as 'buffer': instead of draw into your main device context, draw into the buffer, then copy it into the real device context.
It's easy to implement with this part of code:

void CDrawingArea::OnPaint()
{
    CPaintDC dc(this); // device context for painting
    //
    // Draw with 'double buffering'
    //
    if( m_bDoubleBuffering ) {
        CBitmap bitmap;
        CDC dcMem;
        if( dcMem.CreateCompatibleDC( &dc ) ) {
            bitmap.CreateCompatibleBitmap(&dc, m_rectArea.Width(), m_rectArea.Height() );
            CBitmap* pOldBitmap = dcMem.SelectObject(&bitmap);
            /*************/
            Draw(dcMem);
            /*************/
            dc.BitBlt( m_rectArea.left,
                m_rectArea.top,
                m_rectArea.Width(),
                m_rectArea.Height(),
                &dcMem,
                m_rectArea.left,
                m_rectArea.top,
                SRCCOPY );
            dcMem.SelectObject(pOldBitmap);
        }
    }
    //
    // Draw without 'double buffering'
    //
    else {
        Draw(dc);
    }
}

Where Draw(...) is the function that draws objects into the device context (could be the 'real' or the 'memory' device context). There is another most important effect: the drawing objects are 'clipped' into the device context automatically.
Of course, there is a peformace reduction due to the BitBlt function.

Reading the example code you can found a class called CDrawingArea. This class represents the embryo for a complex class I'm working on. When completed, the user could draw lines, text, ellipses and all others geometric figures. It will allow the user to zoom in and out, pan, copy to clipboard or copy the image into a file, an so on.


Now you can send me a comment or suggestions for next atricles. Thanks.
Feel free to contact me if you found an error (any kind) in this article.


Back to Articles Page