2

我正在运行以下代码,

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);

代码很好。但我在这个矩形周围看到黑色。这是为什么?这是一个示例图像。

4

4 回答 4

4

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

编辑:文档CreateCompatibleBitmap没有说明如何初始化位图,因此您应该使用特定颜色显式初始化位图,正如 Goz 建议的那样,使用FillRect

RECT rc;

rc.left=0;
rc.top=0;
rc.right=c.right-c.left;
rc.bottom=200;

FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(GRAY_BRUSH));

这个例子用灰色填充位图——如果你需要不同的颜色,你可能需要CreateSolidBrush自己的画笔。(完成后别忘了打电话DeleteObject。)

作为旁注,我觉得您的位图设置为 200 的恒定高度有点奇怪——正常的做法是使位图的高度等于窗口的高度(就像对宽度)。

于 2009-09-22T11:12:13.783 回答
1

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

于 2009-09-22T11:12:34.953 回答
0

根据 MSDN http://msdn.microsoft.com/en-us/library/dd162898.aspx

矩形使用当前笔勾勒出轮廓,并使用当前画笔填充。

考虑FillRect改为调用,或在调用Rectangle'.

于 2009-09-22T11:09:16.863 回答
0

我用了:

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

就像一个注释。

于 2009-10-20T10:11:42.463 回答