MFC双缓冲

双缓冲说白就是贴图,将数据全部绘制在缓冲兼容DC上,再将兼容DC的数据一次全部绘制在屏幕上。相较直接在DC上绘图,双缓冲是将绘制数据全部输出,而非分步绘制,并且,可以避免Windows刷新背景色避免闪烁问题。示例如下:

双缓冲:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//在缓冲区作图,最后将缓冲区数据一次全部拷贝至目标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();
}

不用双缓冲:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//直接在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;
    }
}

  

posted @   快雪  阅读(291)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示