首页 > 解决方案 > 如何在 Visual C++ 应用程序中显示图像?

问题描述

我正在尝试在 Visual C++ (2019) 应用程序中显示 PNG 图像。它是一个基于 Win32 对话框的应用程序(我不使用 MFC)来显示包含姓名、地址和照片(800x600 像素)的地址目录。所以,一切都很好,除了照片。我在互联网的帮助下尝试了我所知道的一切,但我仍然无法让它发挥作用。下面给出了我的应用程序的外观示例。

在此处输入图像描述

到目前为止我尝试过的... (1) 添加图像作为资源(您可以在“资源文件”中看到图像)。(2) 创建了显示图像的对话框。(3)在对话框中添加了优化校准。(4) 尝试将图像连接到优化校准... (~问题~)

所以,我仍然没有找到将“Picture Control”连接到“Image”的方法。如果你能告诉我怎么做,或者给我一个链接,它描述了如何做到这一点,我将不胜感激。

标签: winapivisual-c++

解决方案


https://docs.microsoft.com/en-us/windows/win32/api/gdiplusheaders/nf-gdiplusheaders-bitmap-bitmap(constwchar_bool)的构造函数获取任何图像文件并从中创建位图(更易于操作在程序中)。

#include <gdiplusheaders.h>

Bitmap bmp = Bitmap(L"c:\\users\\user\\restofpath\\image.png"); //Get bitmap
HBITMAP hBitmap;
bmp.GetHBITMAP(0, &hBitmap); //Make it an HBITMAP
HDC hdc = GetDC(hwnd); //Get HDC from window handle (can be any window)
HIMAGELIST imageList = ImageList_Create(640, 480, ILC_COLOR24, 1, 10); //Create image list with images of 640 (width) * 480 (height) and 24 bits rgb
ImageList_Add(imageList, hBitmap, NULL); //Add the bitmap to the imageList
BOOL drawn = ImageList_Draw(imageList, 0, hdc, 0, 0, ILD_IMAGE); //Draw the image on the window
DeleteObject(hBitmap);
ImageList_Destroy(imageList);
DeleteObject(hdc);

您可以查看 ImageList_Create 函数以获取其他选项:https ://docs.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-imagelist_create 。特别是标志部分,它允许个性化要绘制的图像类型。如果您想保持 PNG 透明度,您可能需要使用 32 位 DIB。


推荐阅读