简体   繁体   中英

How to draw RGB bitmap to window using GDI?

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?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM