Winapi 比特黑度

Winapi 比特黑度,winapi,bitblt,Winapi,Bitblt,我正在运行以下代码 HDC hdc; HDC hdcMem; HBITMAP bitmap; RECT c; GetClientRect(viewHandle, &c); // instead of BeginPaint use GetDC or GetWindowDC hdc = GetDC(viewHandle); hdcMem = CreateCompatibleDC(hdc); // always create the bitmap for the memdc from th

我正在运行以下代码

HDC hdc;
HDC hdcMem;
HBITMAP bitmap;
RECT c;
GetClientRect(viewHandle, &c);
// instead of BeginPaint use GetDC or GetWindowDC
hdc = GetDC(viewHandle); 
hdcMem = CreateCompatibleDC(hdc); 
// always create the bitmap for the memdc from the window dc
bitmap = CreateCompatibleBitmap(hdc,c.right-c.left,200);

SelectObject(hdcMem, bitmap);

// only execute the code up to this point one time
// that is, you only need to create the back buffer once
// you can reuse it over and over again after that

// draw on hdcMem
// for example  ...
Rectangle(hdcMem, 126, 0, 624, 400);

// when finished drawing blit the hdcMem to the hdc
BitBlt(hdc, 0, 0, c.right-c.left,200, hdcMem, 0, 0, SRCCOPY);

// note, height is not spelled i before e

// Clean up - only need to do this one time as well
DeleteDC(hdcMem);
DeleteObject(bitmap);
ReleaseDC(viewHandle, hdc);
代码很好。但我看到这个长方形周围是黑色的。为什么呢

根据MSDN:

矩形使用当前画笔勾勒,并使用当前画笔填充


请考虑调用FillRect,或者在调用Rectangle之前选择合适的画笔。

位图很可能初始化为全黑。然后,您将绘制一个x坐标126和624之间的白色矩形。因此,x=126左侧和x=624右侧的所有内容都保持黑色

编辑:没有说明位图将如何初始化,因此您应该按照Goz的建议,使用特定颜色显式初始化位图,使用:

此示例以灰色填充位图-如果需要其他颜色,您可能需要使用自己的画笔。做完后别忘了打电话


作为旁注,我发现位图被设置为200的恒定高度有点奇怪-正常的做法是使位图的高度等于窗口的高度,就像宽度一样。

可能是因为您没有将内存位图区域初始化为给定的颜色?尝试将背景填充为不同的颜色,然后在其上绘制白色矩形,看看会发生什么。

我使用了:

    // Fill the background
    hdcMem->FillSolidRect(c, hdcMem->GetBkColor());

请注意。

如何用指定的颜色初始化位图?谢谢Martin,它可以工作。这条路对吗?我想了解为什么我们需要做FillRect。请您在回答中解释一下。这是必要的,因为您不知道CreateCompatibleBitmap创建的位图的初始内容是什么;至少MSDN文档没有指定位图的初始内容,所以您应该初始化它以定义行为。即使画一条线,也会发生同样的情况。我认为问题在于BitBlt您应该保存SelectObject的结果,并在删除之前将其还原,以避免Windows问题,您可能是在避免因DC的发布而崩溃,但它可能有其他副作用:HBITMAP saveBM。。saveBM=SelectObjecthdcMem,位图。。。选择objecthdcmem,saveBM;删除对象位图;这是MFC,不是纯Win32 API
    // Fill the background
    hdcMem->FillSolidRect(c, hdcMem->GetBkColor());