下述代码在OnDraw时绘图:
void CRedrawDemoView::OnDraw(CDC* pDC)
{
CRedrawDemoDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
static const char* pText = "解决重画闪烁问题!";
RECT clRect;
::GetClientRect(m_hWnd, &clRect);
pDC->FillSolidRect(&clRect, RGB(255, 255, 255));
int x = 100, y = 100;
RECT rect = { x - 20, y - 20};
rect.right = rect.left + 160;
rect.bottom = rect.top + 60;
pDC->FillSolidRect(&rect, RGB(0, 255, 0));
pDC->TextOut(x, y, pText, strlen(pText));
}
首先将背景填充白色,然后画一绿色的矩形,再在矩形上输出一段文字,如此过程必然会引起画面闪烁,
解决办法:使用内存DC,先将图形绘制到内存DC,然后拷贝到屏幕,实现无闪烁绘图。
修改后的代码如下:
void CRedrawDemoView::OnDraw(CDC* pDC)
{
CRedrawDemoDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
static const char* pText = "解决重画闪烁问题!";
CRect clRect;
::GetClientRect(m_hWnd, &clRect);
CDC memDC;
memDC.CreateCompatibleDC(pDC);
CBitmap bitmap;
bitmap.CreateCompatibleBitmap(pDC, clRect.Width(), clRect.Height());
CBitmap * pOldBitmap = memDC.SelectObject(&bitmap);
memDC.FillSolidRect(&clRect, RGB(255, 255, 255));
int x = 100, y = 100;
RECT rect = { x - 20, y - 20};
rect.right = rect.left + 160;
rect.bottom = rect.top + 60;
memDC.FillSolidRect(&rect, RGB(0, 255, 0));
memDC.TextOut(x, y, pText, strlen(pText));
pDC->BitBlt(0, 0, clRect.Width(), clRect.Height(), &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
}
也可以在上述代码中加入绘制Bitmap位图代码,注意应该阻止窗口擦除背景,重载OnEraseBkgnd函数
BOOL CRedrawDemoView::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
return TRUE;
// return CView::OnEraseBkgnd(pDC);
}
为易于理解,以上代码未经优化。