c++ 创建窗口并使用 graphics.DrawImage 把图像绘制到窗口上 居中显示
时间: 2024-02-24 13:54:16 浏览: 25
你可以使用 Windows API 和 GDI+ 库来创建窗口并绘制图像。以下是一个简单的示例代码,可以将图像居中显示在窗口中:
```c++
#include <Windows.h>
#include <gdiplus.h>
using namespace Gdiplus;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 初始化 GDI+
ULONG_PTR gdiplusToken;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 注册窗口类
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = TEXT("MyWindowClass");
RegisterClass(&wc);
// 创建窗口
HWND hWnd = CreateWindow(TEXT("MyWindowClass"), TEXT("My Window"),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480,
NULL, NULL, hInstance, NULL);
// 加载图像
Image image(L"image.jpg");
// 获取窗口客户区尺寸
RECT clientRect;
GetClientRect(hWnd, &clientRect);
int clientWidth = clientRect.right - clientRect.left;
int clientHeight = clientRect.bottom - clientRect.top;
// 计算图像居中显示的位置
int imageWidth = image.GetWidth();
int imageHeight = image.GetHeight();
int x = (clientWidth - imageWidth) / 2;
int y = (clientHeight - imageHeight) / 2;
// 绘制图像
HDC hdc = GetDC(hWnd);
Graphics graphics(hdc);
graphics.DrawImage(&image, x, y, imageWidth, imageHeight);
ReleaseDC(hWnd, hdc);
// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 清理 GDI+
GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
在上面的代码中,我们首先使用 GDI+ 库加载了一张图像,并计算出了它居中显示的位置。然后,在窗口创建和绘制的过程中,使用 Windows API 和 GDI+ 库来创建窗口和绘制图像。最后,在消息循环中处理窗口消息,等待窗口关闭。