【发布时间】:2016-05-30 08:44:07
【问题描述】:
我已使用代码here 将PNG 图像加载到BMP 原始矢量std::vector <unsigned char>。现在,我需要将此图像作为背景应用到 WinAPI 窗口,但我不知道如何将其转换为 HBITMAP。也许有人以前做过,或者我可以使用其他格式或变量类型
【问题讨论】:
我已使用代码here 将PNG 图像加载到BMP 原始矢量std::vector <unsigned char>。现在,我需要将此图像作为背景应用到 WinAPI 窗口,但我不知道如何将其转换为 HBITMAP。也许有人以前做过,或者我可以使用其他格式或变量类型
【问题讨论】:
你可以从一开始就使用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")
或在WM_PAINT中使用Gdiplus::Image
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;
}
【讨论】:
WM_PAINT 中绘画,请参阅编辑。如果你真的需要背景刷那么你必须在WM_SIZE中调整图像大小,使用内存dc调整图像大小等来创建一个新的HBITMAP