vc++ windows显示图片
#include <windows.h>
#include <gdiplus.h>
#pragma comment(lib, "Gdiplus.lib")
#include <tchar.h>
using namespace Gdiplus;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 初始化GDI+库
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建窗口
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW, WindowProc, 0, 0, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImageDisplay"), NULL };
RegisterClassEx(&wc);
HWND hwnd = CreateWindow(wc.lpszClassName, _T("Image Display"), WS_OVERLAPPEDWINDOW, 100, 100, 800, 600, NULL, NULL, wc.hInstance, NULL);
if (!hwnd)
{
MessageBox(NULL, _T("窗口创建失败!"), _T("错误"), MB_ICONERROR);
return 1;
}
// 显示窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 进入消息循环
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 清理GDI+资源
GdiplusShutdown(gdiplusToken);
return static_cast<int>(msg.wParam);
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static Image* pImage = nullptr;
switch (uMsg)
{
case WM_CREATE:
// 加载图片
pImage = Image::FromFile(L"E:\\data\\body_pose\\0130\\20240130\\ref\\01301\\frame_0001.jpg");
if (pImage->GetLastStatus() != Ok)
{
MessageBox(hwnd, _T("图片加载失败!"), _T("错误"), MB_ICONERROR);
return -1;
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
Graphics graphics(hdc);
if (pImage)
{// 获取控件的尺寸
RECT clientRect;
GetClientRect(hwnd, &clientRect);
int destWidth = clientRect.right;
int destHeight = clientRect.bottom;
// 计算缩放比例,以使图片填充控件
float scaleX = static_cast<float>(destWidth) / pImage->GetWidth();
float scaleY = static_cast<float>(destHeight) / pImage->GetHeight();
float scale = min(scaleX, scaleY);
int scaledWidth = static_cast<int>(pImage->GetWidth() * scale);
int scaledHeight = static_cast<int>(pImage->GetHeight() * scale);
// 居中显示图片
int xOffset = (destWidth - scaledWidth) / 2;
int yOffset = (destHeight - scaledHeight) / 2;
graphics.DrawImage(pImage, xOffset, yOffset, scaledWidth, scaledHeight);
}
EndPaint(hwnd, &ps);
}
break;
case WM_DESTROY:
if (pImage)
{
delete pImage;
}
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}