如何使用 GDI+ 在 WM_PAINT 中正确绘制

How to properly paint in WM_PAINT with GDI+

我刚开始使用 GDI+,我想知道如何解决创建和处置我拥有的对象的问题。现在所有程序需要做的就是处理重复的 WM_PAINT 消息并每次更新 DrawPie 增加度数。

我在 window 启动时调用了 GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );,在 WM_DESTROY 上调用了 GdiplusShutdown( gdiplusToken );

顶部附近定义的度数全局变量:

volatile double degrees = 0;

这是我的 WM_PAINT:

case WM_PAINT: {
    hdc = BeginPaint( hWnd, &ps );

    Graphics g( hdc );
    Pen p( Color::Green );
    if ( degrees > 0 ) {
        if ( degrees == 360 ) {
            g.DrawEllipse( &p, 0, 0, 100, 100 );
        } else {
            g.DrawPie( &p, 0, 0, 100, 100, -90, degrees );
        }
    }

    EndPaint( hWnd, &ps );
    break;
}

这里是更新度数和更新 window 的函数(在单独的线程中):

void UpdateDegrees() {
    for ( ;; ) {
        if ( globalHWND != NULL ) {
            degrees += 0.1;
            InvalidateRect( globalHWND, NULL, TRUE );
            UpdateWindow( globalHWND );
        }
    }
}

如果我 运行 它会得到一个 "solid" 像 this, which I assume is it just redrawing itself at every angle. It needs to look like this 的饼形,换句话说,在每次重新绘制之前清除图形。 (抱歉,我想我需要 10 个代表才能 post 内联图片)

我知道我没有初始化 and/or 正确处理我的图形,但老实说我不知道​​该怎么做。任何帮助将不胜感激!谢谢。

有很多方法可以做到这一点,标准的方法是处理 WM_ERASEBKGND 消息。

为简单起见,您可以只在剪辑矩形(在 ps 中指定)上填充一个白色矩形,这将清除正在绘制的背景。

SolidBrush backGroundBrush(Color(255,255,255));
Rect clipRect(ps->rcPaint.left, ps.rcPaint.top, ps->rcPaint.right - ps->rcPaint.left, ps->rcPaint.bottom - ps.rcPaint.top);
g.FillRectangle(&backgroundBrush, Rect(ps->rcPaint.left, ps.rcPaint));