双缓冲说白就是贴图,将数据全部绘制在缓冲兼容DC上,再将兼容DC的数据一次全部绘制在屏幕上。相较直接在DC上绘图,双缓冲是将绘制数据全部输出,而非分步绘制,并且,可以避免Windows刷新背景色避免闪烁问题。示例如下:
双缓冲:
//在缓冲区作图,最后将缓冲区数据一次全部拷贝至目标DC void CDoubleBufferView::DrawEx(CDC* pDC) { CRect rect; GetClientRect(rect); //创建兼容当前DC的缓冲DC CDC cacheDC; cacheDC.CreateCompatibleDC(pDC); //创建兼容当前DC的位图 CBitmap bitmap; bitmap.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height()); //将位图选入到缓冲DC CBitmap* pOldBitmap = cacheDC.SelectObject(&bitmap); //填充缓冲DC的背景(默认是黑色) cacheDC.FillSolidRect(0, 0, rect.Width(), rect.Height(), RGB(255, 255, 255)); //在缓冲DC中画图 int x = 0; int y = 0; int step = 2; int idx = 0; while (idx++ < 10000) { cacheDC.MoveTo(x, y); cacheDC.LineTo(rect.Width() - x, y); cacheDC.LineTo(rect.Width() - x, rect.Height() - y); x += step; cacheDC.LineTo(x, rect.Height() - y); y += step; } //将缓冲DC输出到当前DC pDC->BitBlt(0, 0, rect.Width(), rect.Height(), &cacheDC, 0, 0, SRCCOPY); //选回旧的bitmap cacheDC.SelectObject(pOldBitmap); //释放资源 bitmap.DeleteObject(); cacheDC.DeleteDC(); }
不用双缓冲:
//直接在DC上作图 void CDoubleBufferView::Draw(CDC* pDC) { CRect rect; GetClientRect(rect); //在缓冲DC中画图 int x = 0; int y = 0; int step = 2; int idx = 0; while (idx++ < 10000) { pDC->MoveTo(x, y); pDC->LineTo(rect.Width() - x, y); pDC->LineTo(rect.Width() - x, rect.Height() - y); x += step; pDC->LineTo(x, rect.Height() - y); y += step; } }