1

我已使用此处的代码将 PNG 图像加载到 BMP 原始矢量std::vector <unsigned char>中。现在,我需要将此图像作为背景应用到 WinAPI 窗口,但我不知道如何将其转换为HBITMAP. 也许有人以前做过,或者我可以使用另一种格式或变量类型

4

1 回答 1

1

您可以从一开始就使用 Gdiplus,打开 png 文件并获取HBITMAP句柄

//initialize Gdiplus:
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

HBITMAP hbitmap;
HBRUSH hbrush;

Gdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromFile(L"filename.png");
bmp->GetHBITMAP(0, &hbitmap);
hbrush = CreatePatternBrush(hbitmap);

//register classname and assign background brush
WNDCLASSEX wcex;
...
wcex.hbrBackground = hbrush;

CreateWindow...

清理:

DeleteObject(hbrush);
DeleteObject(hbitmap);

delete bmp;

Gdiplus::GdiplusShutdown(gdiplusToken);

您需要包含“gdiplus.h”并链接到“gdiplus.lib”库。默认情况下,头文件应该可用。

在 Visual Studio 中,您可以链接到 Gdiplus,如下所示:

#pragma comment( lib, "Gdiplus.lib")


编辑

Gdiplus::Image用于WM_PAINT

Gdiplus::Image *image = Gdiplus::Image::FromFile(L"filename.png");

WM_PAINT在窗口程序中:

case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);

    if (image)
    {
        RECT rc;
        GetClientRect(hwnd, &rc);
        Gdiplus::Graphics g(hdc);
        g.DrawImage(image, Gdiplus::Rect(0, 0, rc.right, rc.bottom));
    }

    EndPaint(hwnd, &ps);
    return 0;
}
于 2016-02-18T09:51:01.830 回答