How to draw RGB bitmap to window using GDI?

我是研究僧i 提交于 2021-02-11 12:32:19

问题


I have an image in memory with the following byte layout

blue, green, red, alpha (32 bits per pixel)

The alpha is not used.

I want to draw it to a window using GDI. Later I may want to draw only a smaller part of it to the window. But the bitmap in memory is always fixed at a certain width & height.

How can this bitmap drawing operation be done?


回答1:


SetDIBitsToDevice and/or StretchDIBits can be used to draw pixel data directly to a HDC if the pixel data is in a format that can be specified in a BITMAPINFOHEADER. If your color values are not in the correct order you must set the compression to BI_BITFIELDS instead of BI_RGB and append 3 DWORDs as the color mask after BITMAPINFOHEADER in memory.

case WM_PAINT:
{
    RECT rc;
    GetClientRect(hWnd, &rc);
    PAINTSTRUCT ps;
    HDC hDC = wParam ? (HDC) wParam : BeginPaint(hWnd, &ps);

    static const UINT32 pixeldata[] = { ARGB(255,255,0,0), ARGB(255,255,0,255), ARGB(255,255,255,0), ARGB(255,0,0,0) };
    BYTE bitmapinfo[FIELD_OFFSET(BITMAPINFO,bmiColors) + (3 * sizeof(DWORD))];
    BITMAPINFOHEADER &bih = *(BITMAPINFOHEADER*) bitmapinfo;
    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biWidth = 2, bih.biHeight = 2;
    bih.biPlanes = 1, bih.biBitCount = 32;
    bih.biCompression = BI_BITFIELDS, bih.biSizeImage = 0;
    bih.biClrUsed = bih.biClrImportant = 0;
    DWORD *pMasks = (DWORD*) (&bitmapinfo[bih.biSize]);
    pMasks[0] = 0xff0000; // Red
    pMasks[1] = 0x00ff00; // Green
    pMasks[2] = 0x0000ff; // Blue

    StretchDIBits(hDC, 0, 0, rc.right, rc.bottom, 0, 0, 2, 2, pixeldata, (BITMAPINFO*) &bih, DIB_RGB_COLORS, SRCCOPY);

    return !(wParam || EndPaint(hWnd, &ps));
}


来源:https://stackoverflow.com/questions/56691569/how-to-draw-rgb-bitmap-to-window-using-gdi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!