初学者 在 MFC C++ 中,为什么设备上下文需要创建一个旧的 Font/Bitmap/etc 指针,然后在最后选择对象()?

Beginner In MFC C++, why does the device context need to create an old Font/Bitmap/etc pointer and then selectObject() it at the end?

例证:

void CMainWindow::OnPaint ()
{
    CRect rect;
    GetClientRect (&rect);

    CPaintDC dc (this);
    dc.SetViewportOrg (rect.Width () / 2, rect.Height () / 2);
    dc.SetBkMode (TRANSPARENT);

    for (int i=0; i<3600; i+=150) {
        LOGFONT lf;
        ::ZeroMemory (&lf, sizeof (lf));
        lf.lfHeight = 160;
        lf.lfWeight = FW_BOLD;
        lf.lfEscapement = i;
        lf.lfOrientation = i;
        ::lstrcpy (lf.lfFaceName, _T ("Arial"));

        CFont font;
        font.CreatePointFontIndirect (&lf);

        CFont* pOldFont = dc.SelectObject (&font);
        dc.TextOut (0, 0, CString (_T ("          Hello, MFC")));

        //WHY THIS LINE?
        dc.SelectObject (pOldFont);
    }
}

代码在围绕原点(移动到 window 的中心)的圆圈中打印“Hello, MFC”。

为什么创建了CFont 指针然后dc 选择它作为字体?这只是良好的编程习惯还是这个应用程序真的需要它?

我在网上看到类似的代码使用位图和其他设备上下文对象执行此操作。目的是什么?

当我删除最后一行代码时,没有任何变化。先谢谢您的帮助。

Device Context:

A device context is a structure that defines a set of graphic objects and their associated attributes, as well as the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for painting and filling, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations, and a path for painting and drawing operations.

在任何时候,只有一个 图形对象 被选择到设备上下文中。由于系统在创建设备上下文时将一组默认对象存储到设备上下文中,因此当设备上下文交还给系统进行清理时,应用程序必须保留该状态。就是这样

dc.SelectObject (pOldFont);

负责.

此要求记录在 SelectObject 下:

This function returns the previously selected object of the specified type. An application should always replace a new object with the original, default object after it has finished drawing with the new object.


注意:这与 MFC 无关,而是 Windows GDI。 MFC 仅仅实现了一个自动资源管理包装器。状态管理仍然需要显式代码。