使用资源中的PNG图标显示Win32弹出菜单

Show Win32 popup menu with PNG icons from resources

本文关键字:Win32 显示 菜单 图标 PNG 资源      更新时间:2023-10-16

我已经很久没有处理Win32菜单了。我需要在Win32上下文弹出菜单中添加一些PNG图标。当然,我想在这个过程中保留PNG的透明度和所有的每像素alpha。这可能吗?

我在考虑使用SetMenuItemBitmaps。这是要走的路吗?

我将我的PNG导入为"PNG"资源,但我似乎既不能用LoadBitmap也不能用LoadImage加载它们。我发现了一些关于使用Gdi+的建议,但显然我不会绘制菜单——系统会的。

似乎有一种方法可以从Gdi+Bitmap中获得HBITMAP,但在这个过程中,似乎所有的alpha都丢失了。AFAIK,HBITMAP可以愉快地托管阿尔法信息。

您需要GDI+来加载PNG。然后,您需要创建一个正确大小的32位alpha位图,在位图上创建一个Graphics,并使用DrawImage将PNG复制到位图中。这将为您提供一个带有alpha通道的位图。

类似这样的东西:

Image*  pimgSrc = Image::FromFile("MyIcon.png"L, FALSE);
Bitmap* pbmpImage = new Bitmap(
    iWidth, iHeight, 
    PixelFormat32bppARGB
);
Graphics* pgraphics = Graphics::FromImage(bmpImage))
{
    // This draws the PNG onto the bitmap, scaling it if necessary.
    // You may want to set the scaling quality 
    graphics->DrawImage(
        imageSrc,
        Rectangle(0,0, bmpImage.Width, bmpImage.Height),
        Rectangle(0,0, imgSrc.Width, imgSrc.Height),
        GraphicsUnitPixel
    );
}
// You can now get the HBITMAP from the Bitmap object and use it.
// Don't forget to delete the graphics, image and bitmap when done.

也许您可以使用icon?

以下是我使用图标而不是PNG:的原因

  1. Win32 API有很好的支持图标,而且绘制图标相对容易得多,因为不需要GDI+
  2. 图标还支持8位透明度(就像PNG一样)
  3. 图标可以是任何像素大小(就像PNG一样)
  4. 图标可以很容易地作为资源嵌入到可执行文件中
  5. 图标可以通过Visual Studio进行编辑

要从资源或文件加载图标,请使用:

LoadImage()

要绘制图标,请使用:

DrawIcon() or DrawIconEx()