MFC使用HDC和StretchDIBits怎么实现双缓冲显示 代码
时间: 2024-02-17 07:01:38 浏览: 198
实现双缓冲技术.h---MFC
使用HDC和StretchDIBits实现双缓冲显示的步骤如下:
1. 创建两个内存DC(Device Context)和两个内存位图(Bitmap),分别用来保存前后两帧图像。
```
CDC* pDC = GetDC();
CRect rect;
GetClientRect(&rect);
CDC memDC1, memDC2;
CBitmap bmp1, bmp2;
memDC1.CreateCompatibleDC(pDC);
memDC2.CreateCompatibleDC(pDC);
bmp1.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height());
bmp2.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height());
memDC1.SelectObject(&bmp1);
memDC2.SelectObject(&bmp2);
ReleaseDC(pDC);
```
2. 在每一帧绘制前,将前后两个内存DC的位图进行交换,这样就可以在绘制当前帧时,不影响上一帧的显示。
```
CDC* pMemDC;
CBitmap* pBmp;
if (m_bUseMemDC1) {
pMemDC = &memDC1;
pBmp = &bmp1;
} else {
pMemDC = &memDC2;
pBmp = &bmp2;
}
m_bUseMemDC1 = !m_bUseMemDC1;
```
3. 绘制当前帧到内存DC中。
```
// 绘制当前帧到pMemDC中
// ...
```
4. 将内存DC中的位图通过StretchDIBits函数绘制到屏幕上。
```
CDC* pDC = GetDC();
CRect rect;
GetClientRect(&rect);
StretchDIBits(pDC->GetSafeHdc(), 0, 0, rect.Width(), rect.Height(), 0, 0, rect.Width(), rect.Height(), pBmp->GetBits(), &m_bmpInfo, DIB_RGB_COLORS, SRCCOPY);
ReleaseDC(pDC);
```
完整代码如下:
```
CDC* pDC = GetDC();
CRect rect;
GetClientRect(&rect);
CDC memDC1, memDC2;
CBitmap bmp1, bmp2;
memDC1.CreateCompatibleDC(pDC);
memDC2.CreateCompatibleDC(pDC);
bmp1.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height());
bmp2.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height());
memDC1.SelectObject(&bmp1);
memDC2.SelectObject(&bmp2);
ReleaseDC(pDC);
while (true) {
CDC* pMemDC;
CBitmap* pBmp;
if (m_bUseMemDC1) {
pMemDC = &memDC1;
pBmp = &bmp1;
} else {
pMemDC = &memDC2;
pBmp = &bmp2;
}
m_bUseMemDC1 = !m_bUseMemDC1;
// 绘制当前帧到pMemDC中
// ...
pDC = GetDC();
StretchDIBits(pDC->GetSafeHdc(), 0, 0, rect.Width(), rect.Height(), 0, 0, rect.Width(), rect.Height(), pBmp->GetBits(), &m_bmpInfo, DIB_RGB_COLORS, SRCCOPY);
ReleaseDC(pDC);
}
```
阅读全文