【发布时间】:2014-05-13 22:01:41
【问题描述】:
我一定是做错了什么或者错过了什么,因为我真正想要的只是将一个矩形渲染成一个位图,这样我就可以在它上面进行 CreateWindowEx() 了。有谁知道我错过了什么?
HDC hdc = GetDC(hWnd);
// Create Pen and brush for the rectangle
HPEN pn = CreatePen(style, stroke, pen);
HBRUSH br = CreateSolidBrush(brush);
// Create a compatible bitmap and DC from the window DC with the correct dimensions
HDC bm_hdc = CreateCompatibleDC(hdc);
HBITMAP hImage = CreateCompatibleBitmap(bm_hdc, sz.x, sz.y);
// Select the bitmap, pen, brush into the DC
HGDIOBJ bm_obj = SelectObject(bm_hdc, hImage);
HGDIOBJ pn_obj = SelectObject(bm_hdc, pn);
HGDIOBJ br_obj = SelectObject(bm_hdc, br);
// Draw the rectangle into the compatible DC with the bitmap selected
::Rectangle(bm_hdc, xPos, yPos, xPos + xSize, yPos + ySize);
// Restore the old selections
SelectObject(bm_hdc, br_obj);
SelectObject(bm_hdc, pn_obj);
SelectObject(bm_hdc, bm_obj);
// Delete the not needed DC, pen and brush
DeleteDC(bm_hdc);
DeleteObject(br);
DeleteObject(pn);
ReleaseDC(hWnd, hdc);
// Create the window and send a message to set the static image
HWND win = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | SS_BITMAP | WS_VISIBLE, pos.x, pos.y, sz.x, sz.y, hWnd, NULL, hInst, NULL)));
HGDIOBJ obj = (HGDIOBJ)SendMessage(win, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hImage);
// Delete the old image
if (obj)
DeleteObject(hImage);
嗯...但这不起作用...我得到的只是一个完全黑色的区域,而不是我绘制的矩形。任何想法为什么?我是否需要在设备上下文之间创建另一个 DC 和 BitBlt()?
【问题讨论】:
-
嗯,您的“删除旧图像”删除了新图像。旧图像是 SendMessage 的返回值
-
谢谢...我刚刚注意到,但这似乎不是导致问题的原因。
-
你为什么不认为@RaymondChen 是正确的?在图像有机会显示之前将其删除肯定符合给定的症状。
-
我已经对其进行了修改,以表明 ObjHandle 实际上是 CreateWindow 返回的 HWND。在我的实际代码中,而不是这里的小附件,我实际上并没有删除对象,我仍然得到没有矩形的黑色窗口。
-
如果你的图片有alpha像素,那么返回的位图就是控件创建的副本,否则就是你传递的原图。检查您的图像以查看是否需要删除它。如果没有 alpha 像素,则您的图像需要具有与控件相同的生命周期才能使用,相反的情况下,您需要在控件销毁后将两者都删除,否则会导致资源泄漏。