【发布时间】:2017-05-20 17:47:03
【问题描述】:
我正在开发一个 GUI 类,并且我创建了一个方法,该方法可以根据像素数组在窗口上绘制位图。 我想用同样的方法在那个位图上画。另外,我使用屏幕外 DC 来避免闪烁。
这是我的代码:
int width(m_rect.right - m_rect.left), height(m_rect.bottom - m_rect.top); // m_rect is the RECT of the bitmap, initialized beforehand
BITMAPINFOHEADER bih = { 0 };
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biCompression = BI_RGB;
bih.biBitCount = 32;
bih.biPlanes = 1;
bih.biWidth = width; // = 100, for instance
bih.biHeight = height; // = 100, same here
HDC dc = CreateCompatibleDC(hdc); // "hdc" is the DC of my window
HBITMAP bmp = CreateDIBitmap(hdc, &bih, CBM_INIT, m_data, &m_bmpInfo, DIB_RGB_COLORS); // creates a 32-bit device-independent bitmap
HGDIOBJ oldObj = SelectObject(dc, bmp);
RECT r = { m_rect.left + 10, m_rect.top + 10, m_rect.right - 10, m_rect.bottom - 10 };
HBRUSH brush = CreateSolidBrush(0xff);
FillRect(dc, &r, brush); // this line doesn't work!
DeleteObject(brush);
BitBlt(hdc, m_rect.left, m_rect.top, width, height, dc, 0, 0, SRCCOPY);
SelectObject(dc, oldObj);
DeleteObject(bmp);
DeleteDC(dc);
问题是我无法在位图上绘制任何内容。它在屏幕上正确绘制,但我无法在其上绘制。与其他绘图功能相同:矩形、圆形矩形等。此外,性能对我来说很重要。这段代码越快,我就越开心。因此,如果您对性能改进有任何建议,请告诉我。
任何帮助将不胜感激。 提前谢谢你。
【问题讨论】:
-
m_rect.left和m_rect.top是什么?我的猜测是,您在位图边界之外进行绘画。落入dc的坐标在ReCT{0, 0, width, height}之内。你在BitBlt调用中做对了,但在FillRect调用中却没有。 -
天哪,你是对的! m_rect.left 和 m_rect.top 是我的位图左上角的绝对坐标。我不敢相信我混淆了绝对坐标和相对坐标...非常感谢您的帮助!!!
-
由于您关心速度,您可能想尝试使用
CreateCompabitBitmap而不是CreateDiBitmap。我已经很多年没有比较它们了,但至少在我比较的时候,兼容的位图通常要快很多。 -
感谢您的帖子,但我认为无论如何我都必须使用 CreateDIBitmap,因为我需要从像素数组创建位图,而使用 CreateCompatibleBitmap 无法做到这一点。还有其他方法可以从原始像素数据创建位图吗?
标签: c++ windows winapi gdi visual-studio-2017