通过将HICON绘制到HBITMAP,从现有HICON创建HICON

时间:2012-09-13 04:20:33

标签: c++ winapi gdi

作为更大项目的一部分,我试图通过首先将该图标绘制到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;
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

也许你想检查位图本身是黑色的,还是好的,只有图标是黑色的。根据我的经验(我对此没有合理的解释),问题出在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);

答案 1 :(得分:0)

ICONINFO nfo;
GetIconInfo(icon_, &nfo);
MyDrawSomethingOnIcon(nfo.hbmColor);
HICON new_icon = CreateIconIndirect(&nfo);

您需要做的就是实施MyDrawSomethingOnIcon。当然,当它们不再使用时,您必须释放所有使用过的图标和位图。 MSDN将帮助您处理=)