简体   繁体   English

如何利用设备环境

[英]How to draw into device context

I have a bitmap image in form of array of 32-bit integers (ARGB pixels: uint32 *mypixels ) and int width and int height . 我有一个32位整数数组形式的位图图像(ARGB像素: uint32 *mypixels )以及int widthint height I need to output them to a printer. 我需要将它们输出到打印机。

I have the printer context: HDC hdcPrinter; 我有打印机上下文: HDC hdcPrinter;

As I learned, I need first to create a compatible context: 据我了解,我首先需要创建一个兼容的上下文:

HDC hdcMem = CreateCompatibleDC(hdcPrinter);

Then I need to create an HBITMAP object, select it into the compatible context, and render: 然后,我需要创建一个HBITMAP对象,将其选择到兼容的上下文中,然后进行渲染:

HBITMAP hBitmap = ...?
SelectObject(hdcMem, hBitmap);
BitBlt(printerContext, 0, 0, width, height, hdcMem, 0, 0, SRCCOPY);

And finally clean up: 最后清理:

DeleteObject(hBitmap);
DeleteDC(hdcMem);

My question is how do I create an HBITMAP object and put mypixels into it? 我的问题是如何创建HBITMAP对象并将mypixels放入其中?

I found two options: 我发现了两个选择:

  1. HBITMAP hBitmap = CreateCompatibleBitmap(hdcPrinter, width, height);

    Looks good, but how do mypixels get into this bitmap? 看起来不错,但是mypixels如何进入该位图?

  2. HBITMAP hBitmap = CreateDIBSection(hdcPrinter /*or hdcMem?*/, ...);

    Will it work? 能行吗 Is it better than option 1.? 它比选项1好吗?

This function creates a bitmap and sets it to an initial image. 此功能创建一个位图并将其设置为初始图像。 Irt's a bit fiddly to access the bits directly, but it can be done. 直接访问这些位有点麻烦,但这是可以做到的。

HBITMAP MakeBitmap(unsigned char *rgba, int width, int height, VOID **buff)
{
    VOID *pvBits;          // pointer to DIB section 
    HBITMAP answer;
    BITMAPINFO bmi;
    HDC hdc;
    int x, y;
    int red, green, blue, alpha;

    // setup bitmap info   
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = height;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;         // four 8-bit components 
    bmi.bmiHeader.biCompression = BI_RGB;
    bmi.bmiHeader.biSizeImage = width * height * 4;

    hdc = CreateCompatibleDC(GetDC(0));
    answer = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x0);
    for (y = 0; y < height; y++)
    {
        for (x = 0; x < width; x++)
        {
            red = rgba[(y*width + x) * 4];
            green = rgba[(y*width + x) * 4 + 1];
            blue = rgba[(y*width + x) * 4 + 2];
            alpha = rgba[(y*width + x) * 4 + 3];
            red = (red * alpha) >> 8;
            green = (green * alpha) >> 8;
            blue = (blue * alpha) >> 8;
            ((UINT32 *)pvBits)[(height - y - 1) * width + x] = (alpha << 24) | (red << 16) | (green << 8) | blue;
        }
    }
    DeleteDC(hdc);

    *buff = pvBits;

    return answer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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