通过调用SetDIBits直接修改位图数据。下面的示例在黑色背景上画了一个十字。
- void CTest5Dlg::OnOK()
- {
- // TODO: Add extra validation here
- CClientDC dc(this);
- CDC memDC;
- memDC.CreateCompatibleDC(&dc);
- CBitmap bmp;
- bmp.CreateCompatibleBitmap(&dc, 300, 200);
- memDC.SelectObject(&bmp);
- BITMAPINFO bmpInfo;
- bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- bmpInfo.bmiHeader.biWidth = 300;
- bmpInfo.bmiHeader.biHeight = -200;
- bmpInfo.bmiHeader.biPlanes = 1;
- bmpInfo.bmiHeader.biBitCount = 24;
- bmpInfo.bmiHeader.biCompression = BI_RGB;
- bmpInfo.bmiHeader.biSizeImage = 0;
- bmpInfo.bmiHeader.biXPelsPerMeter = 3000;
- bmpInfo.bmiHeader.biYPelsPerMeter = 3000;
- bmpInfo.bmiHeader.biClrUsed = 0;
- bmpInfo.bmiHeader.biClrImportant = 0;
- long nLnBytes = (bmpInfo.bmiHeader.biWidth*3+3)/4*4;
- BYTE *pData = new BYTE[nLnBytes*abs(bmpInfo.bmiHeader.biHeight)];
- //清成黑色
- memset(pData,0,nLnBytes*abs(bmpInfo.bmiHeader.biHeight));
- //画一个十字
- for(int i=10; i<90; i++)
- {
- //横线, 黄色
- pData[50*nLnBytes+i*3+1] = 255; //g
- pData[50*nLnBytes+i*3+2] = 255; //r
- //竖线, 蓝色
- pData[i*nLnBytes+50*3] = 255; //b
- }
- SetDIBits(dc.m_hDC, bmp, 0, abs(bmpInfo.bmiHeader.biHeight), pData, &bmpInfo, DIB_RGB_COLORS);
- delete []pData;
- dc.BitBlt(0, 0, bmpInfo.bmiHeader.biWidth, abs(bmpInfo.bmiHeader.biHeight), &memDC, 0, 0, SRCCOPY);
- }
效果图: