c++ 创建窗口并使用 graphics.DrawImage 把图像绘制到窗口上
时间: 2024-02-23 22:00:50 浏览: 29
您可以使用 Windows API 来创建窗口并使用 GDI+ 绘制图像。以下是一个示例代码:
```c++
#include <windows.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
// 初始化 GDI+
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建窗口
HWND hWnd;
WNDCLASSEXW wcex = { sizeof(WNDCLASSEXW) };
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.lpszClassName = L"MyWindowClass";
RegisterClassExW(&wcex);
hWnd = CreateWindowW(wcex.lpszClassName, L"Window Title",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
800, 600, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg = {};
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 释放 GDI+
Gdiplus::GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static Gdiplus::Image* pImage = nullptr;
switch (message)
{
case WM_CREATE:
// 加载图像
pImage = Gdiplus::Image::FromFile(L"path/to/image.jpg");
if (!pImage)
{
return -1;
}
break;
case WM_PAINT:
{
// 绘制图像
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
Gdiplus::Graphics graphics(hdc);
graphics.DrawImage(pImage, 0, 0, 800, 600);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
// 释放资源
delete pImage;
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
在该示例代码中,我们通过 GDI+ 的 `Image::FromFile` 方法加载了一张图像,并在窗口的 `WM_PAINT` 消息中使用 `graphics.DrawImage` 方法将图像绘制到窗口上。注意,在 `WM_DESTROY` 消息中需要释放图像资源。