Explanation of Double Buffering
If you have to draw repeatedly to the screen in a short period of time, then when you keep drawing step by step to the DC
, it updates the Window again and again which makes the screen flicker.
To avoid this, we first draw to a DC
in memory (see the CDC MemDC
and CBitmap MemBitmap
declarations), and we store the resultant drawing in a memory bitmap. After all the drawing has been completed,
we move the bitmap from the memory to the screen in a fast single bitblt
call. Thus, we only need to draw once to the screen which avoids flickering totally. This principle is called Double Buffering.
Example code
This example assumes that you are going to draw filled rectangles onto the screen. It generates random shades of green to fill that rectangle.
Use this code in your view class's OnDraw()
function if you are using Doc/View architecture or if you are using a dialog based application, then you can add this code in the OnPaint
Function.
CRect rcClient;
GetClientRect(rcClient);
CDC MemDC,*pDC;
CBitmap MemBitmap;
pDC = this->GetDC()
MemDC.CreateCompatibleDC(pDC);
MemBitmap.CreateCompatibleBitmap(pDC,rcClient.right,rcClient.bottom);
CBitmap *pOldBitmap = MemDC.SelectObject(&MemBitmap);
CBrush bkBrush(HS_FDIAGONAL,RGB(0,rand()%255,0));
MemDC.FillRect(rcClient,&bkBrush);
pDC->BitBlt(0,0,rcClient.right,rcClient.bottom,&MemDC,0,0,SRCCOPY);
MemDC.SelectObject(pOldBitmap);
Note 1 : Gets the coordinates of the bounding rectangle.
Note 2 : Creates a brush with random shades of green. The rand()%255
generates a value between 0 and 255 randomly.
Note 3 : Copies the bitmap from the memory dc
to the pdc
using a fast bitblt
function call.
I hope that i have made it clear to you. Good Luck.