在绘制窗口之前将窗口的背景设置为不寻常的图案

时间:2017-05-31 07:07:08

标签: winapi mfc

我有一个窗口(CWnd对象),我正在绘制一个位图图像。

在此之前,我想将窗口的背景设置为特定模式。

模式可能会不时变化。

如果我理解正确,那么我需要覆盖窗口的OnCtlColor函数,并返回与我想要的模式兼容的画笔(根据内部数据结构重新计算)。

  1. 我是否走在正确的轨道上?

  2. 图案相当不规则。它由"斑马条纹组成,所有这些都具有相同的宽度,但(可能是)具有不同的高度。以下是一个示例:

  3. enter image description here

    甚至可以创建具有这种模式的画笔吗?

    如果是,那么下列哪项功能最合适:

    • CBrush::CreateBrushIndirect
    • CBrush::CreateDIBPatternBrush
    • CBrush::CreateHatchBrush
    • CBrush::CreatePatternBrush

    谢谢。

1 个答案:

答案 0 :(得分:2)

我甚至不愿意用刷子打扰。此示例使用FillSolidRect绘制一堆条纹,并以屏幕高度百分比绘制条带高度。如果你使用绝对值,应该很容易调整。

BOOL CChildView::OnEraseBkgnd(CDC* pDC)
{
    CRect clientRect;
    GetClientRect(clientRect);

    const auto savedDC = pDC->SaveDC();

    // Make the co-ordinates system behave like percentages
    {
        pDC->SetMapMode(MM_ANISOTROPIC);
        pDC->SetWindowExt(100, 100);
        pDC->SetViewportExt(clientRect.right, clientRect.bottom);
    }

    // pair requires #include <utility>
    std::pair<int, COLORREF> stripeData[] =
    {
        { 8, RGB(220,220,220) },    // 8% of window height, light grey
        { 17, RGB(165,165,165) },   // 17% of window height, dark grey
        { 12, RGB(220,220,220) },   // etc. These should total 100%
        { 7, RGB(165,165,165) },
        { 23, RGB(220,220,220) },
        { 33, RGB(165,165,165) }
    };

    // NOTE: FillSolidRect changes the background color, so restore it at the
    // end of the function. RestoreDC will handle this; otherwise save the
    // GetBkColor return value and restore it by calling SetBkColor

    //auto oldBkColor = pDC->GetBkColor();

    // Draw the stripes
    CRect stripeRect{0,0,100,0};
    for (auto const& data : stripeData)
    {
        stripeRect.bottom = stripeRect.top + data.first;
        pDC->FillSolidRect(stripeRect, data.second);
        stripeRect.OffsetRect(0, data.first);
    }

    //pDC->SetBkColor(oldBkColor);

    pDC->RestoreDC(savedDC);

    return TRUE;
}