【发布时间】:2021-02-17 08:10:07
【问题描述】:
我正在尝试使用 GDI+ 从我的资源文件中显示 PNG 图像。
#include <Windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
#pragma comment(lib, "dwmapi.lib")
...
auto CALLBACK BorderlessWindow::WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) noexcept -> LRESULT {
if (auto window_ptr = reinterpret_cast<BorderlessWindow*>(::GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
auto& window = *window_ptr;
switch (msg) {
case WM_PAINT: {
HDC hdc;
PAINTSTRUCT ps;
hdc = BeginPaint(hwnd, &ps);
Graphics graphics(hdc);
Image image(L"C:\\my_image.png");
graphics.DrawImage(&image, 50, 50);
EndPaint(hwnd, &ps);
break;
}
}
}
return ::DefWindowProcW(hwnd, msg, wparam, lparam);
}
...
int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
// Initialize GDI+.
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
...
GdiplusShutdown(gdiplusToken);
}
上面的代码适用于本地文件,我想使用我添加到项目中的资源文件。我该怎么做?
【问题讨论】:
-
注意这里的位图名称应该是:
MAKEINTRESOURCE(IDB_YOUR_BITMAP_RESOURCE_ID) -
...但是资源必须保存在位图分类下。我不确定您是否可以使用 PNG 来做到这一点(VS 自动将它们保存到他们自己的分类中,这个构造函数无法加载)。你可以通过
Gdiplus::Bitmap::Bitmap(IStream*, BOOL)解决这个问题,但这可能有点太复杂了。 -
@IWonderWhatThisAPIDoes -
Gdiplus::Bitmap bitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PNG1));这不适用于 PNG。我尝试使用 BMP 并且它有效。我需要它来处理 PNG。 -
@Papilion 是的。您可以尝试强制将 PNG 标记为资源中的位图(以便构造函数识别它,但我不确定 PNG 可以标记为位图)或使用成像组件。
标签: c++ winapi visual-studio-2019 gdi+