问题描述
我一直试图在 8bpp 灰度位图上绘制但没有成功.这是我的一些尝试.也许有人可以指出我做错了什么.
I've been attempting to draw on an 8bpp grayscale bitmap without success. Here are some of my attempts. Maybe someone can point out what I'm doing wrong.
==================================================
===================================================
尝试 1:创建、选择和绘制:
Attempt 1: Create, select, and draw:
在构造函数中:
CBitmap bm;
bm.CreateBitmap (200, 200, 1, 8, NULL);
在 OnDraw 中:
In OnDraw:
CDC *mdc=new CDC ();
HGDIOBJ tmp = mdc->SelectObject(bm);
结果:tmp 为NULL,表示失败.
Result: tmp is NULL, indicating failure.
==================================================
===================================================
尝试 2:创建DIBSection
Attempt 2: CreateDIBSection
在构造函数中:
HBITMAP hbm;
BITMAPINFOHEADER bih;
BITMAPINFO bi;
HANDLE hb;
CDC* myDc = new CDC ();
HDC hdc = myDc->GetSafeHdc ();
void* bits;
RGBQUAD rq [256];
initBi ();
hbm = CreateDIBSection (hdc, &bi, DIB_RGB_COLORS, &bits, NULL, 0);
...
void CEightBitDrawingView::initBi()
{
bih.biSize = sizeof (BITMAPINFOHEADER);
bih.biWidth = 200;
bih.biHeight = -200;
bih.biPlanes = 1;
bih.biBitCount = 8;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 14173;
bih.biYPelsPerMeter = 14173;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
memset ((void *) rq, 0, 256 * sizeof (RGBQUAD));
bi.bmiHeader = bih;
bi.bmiColors = rq;
}
结果:这甚至无法编译,因为 BITMAPIINFO bmiColors 成员定义为:RGBQUAD bmiColors[1];
Result: This doesn't even compile because the BITMAPINFO bmiColors member is defined as: RGBQUAD bmiColors[1];
所以不会接受超过一种 RGB 颜色.事实上,我分配给该成员的任何内容都无法编译!(他们能不能让它变得更复杂!?)
so won't accept more than one RGB color. In fact, nothing I assign to this member compiles! (Could they possibly make it any more complex!?)
任何建议将不胜感激!谢谢!
Any suggestions would be appreciated! Thanks!
==================================================
===================================================
推荐答案
这里.演示如何 - 在非托管环境中 - 在堆栈上分配动态大小的结构、填充它并将其传递给 CreateDIBSection 的代码.
Here. Code that demonstrates how to - in a not managed world - allocate a dynamically sized structure on the stack, fill it in and pass it to CreateDIBSection.
#include <malloc.h>
HBITMAP CreateGreyscaleBitmap(int cx, int cy)
{
BITMAPINFO* pbmi = (BITMAPINFO*)alloca( sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
pbmi->bmiHeader.biSize = sizeof (pbmi->bmiHeader);
pbmi->bmiHeader.biWidth = cx;
pbmi->bmiHeader.biHeight = cy;
pbmi->bmiHeader.biPlanes = 1;
pbmi->bmiHeader.biBitCount = 8;
pbmi->bmiHeader.biCompression = BI_RGB;
pbmi->bmiHeader.biSizeImage = 0;
pbmi->bmiHeader.biXPelsPerMeter = 14173;
pbmi->bmiHeader.biYPelsPerMeter = 14173;
pbmi->bmiHeader.biClrUsed = 0;
pbmi->bmiHeader.biClrImportant = 0;
for(int i=0; i<256; i++)
{
pbmi->bmiColors[i].rgbRed = i;
pbmi->bmiColors[i].rgbGreen = i;
pbmi->bmiColors[i].rgbBlue = i;
pbmi->bmiColors[i].rgbReserved = 0;
}
PVOID pv;
return CreateDIBSection(NULL,pbmi,DIB_RGB_COLORS,&pv,NULL,0);
}
这篇关于绘制 8bpp 灰度位图(非托管 C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!