作为更大项目的一部分,我试图通过将现有图标绘制为HBITMAP,然后将其转换回HICON,从现有HICON创建HICON。 (这将允许我修改图标,例如,通过在其上绘制文本。)

不幸的是,该图标显示为黑色正方形。这是我的代码:

bool createIcon()
{
  bool ret = false;

  // get context of window
  HDC context = GetDC(window_);
  if (context != NULL)
  {
    // create a buffer context
    HDC buffer = CreateCompatibleDC(context);
    if (buffer != NULL)
    {
      PatBlt(buffer, 0, 0, iconSize_, iconSize_, WHITENESS);

      // create a bitmap for our use
      HBITMAP bitmap = CreateCompatibleBitmap(context, iconSize_, iconSize_);
      if (bitmap != NULL)
      {
        HBITMAP oldBitmap;

        // select the bitmap with the buffer
        oldBitmap = reinterpret_cast<HBITMAP>(SelectObject(buffer, bitmap));
        if (oldBitmap != NULL)
        {
          // draw the icon
          if (DrawIcon(buffer, 0, 0, icon_))
          {
            if (icon_ != NULL)
              DestroyIcon(icon_);

            ImageList_RemoveAll(imageList_);
            if (ImageList_Add(imageList_, bitmap, NULL) != -1)
            {
              icon_ = ImageList_GetIcon(imageList_, 0, ILD_NORMAL);
              if (icon_ != NULL)
                ret = true;
            }
          }
          SelectObject(buffer, oldBitmap);
        }
        DeleteObject(bitmap);
      }
      DeleteDC(buffer);
    }
    DeleteDC(context);
  }
  return ret;
}

有任何想法吗?

最佳答案

也许您想检查位图本身是否为黑色,或者它是否良好并且仅图标为黑色。根据我的经验(尽管我对此没有合理的解释),问题出在CreateCompatibleBitmap周围,我希望位图本身已经是黑色的。请尝试CreateDIBSection。这曾经为我工作:

//HBITMAP hBitmap = CreateCompatibleBitmap(hDc, ResourceIconColorBitmap.bmWidth, ResourceIconColorBitmap.bmHeight);
BITMAPINFO BitmapInformation;
ZeroMemory(&BitmapInformation, sizeof BitmapInformation);
BitmapInformation.bmiHeader.biSize = sizeof BitmapInformation.bmiHeader;
BitmapInformation.bmiHeader.biWidth = ResourceIconColorBitmap.bmWidth;
BitmapInformation.bmiHeader.biHeight = ResourceIconColorBitmap.bmHeight;
BitmapInformation.bmiHeader.biPlanes = 1;
BitmapInformation.bmiHeader.biBitCount = 24;
VOID* pvBits;
HBITMAP hBitmap = CreateDIBSection(hDc, &BitmapInformation, DIB_RGB_COLORS, &pvBits, NULL, 0);

关于c++ - 通过将现有的HICON绘画到HBITMAP来创建HICON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12399357/

10-14 16:47