如何从 HICON 中确定图标的大小?
Posted
技术标签:
【中文标题】如何从 HICON 中确定图标的大小?【英文标题】:How to determine the size of an icon from a HICON? 【发布时间】:2009-12-16 09:38:27 【问题描述】:我有一个由HICON
句柄标识的图标,我想以自定义控件为中心绘制该图标。
如何确定图标的大小,以便计算出正确的绘制位置?
【问题讨论】:
【参考方案1】:这是一个 C++ 版本的代码:
struct MYICON_INFO
int nWidth;
int nHeight;
int nBitsPerPixel;
;
MYICON_INFO MyGetIconInfo(HICON hIcon);
// =======================================
MYICON_INFO MyGetIconInfo(HICON hIcon)
MYICON_INFO myinfo;
ZeroMemory(&myinfo, sizeof(myinfo));
ICONINFO info;
ZeroMemory(&info, sizeof(info));
BOOL bRes = FALSE;
bRes = GetIconInfo(hIcon, &info);
if(!bRes)
return myinfo;
BITMAP bmp;
ZeroMemory(&bmp, sizeof(bmp));
if(info.hbmColor)
const int nWrittenBytes = GetObject(info.hbmColor, sizeof(bmp), &bmp);
if(nWrittenBytes > 0)
myinfo.nWidth = bmp.bmWidth;
myinfo.nHeight = bmp.bmHeight;
myinfo.nBitsPerPixel = bmp.bmBitsPixel;
else if(info.hbmMask)
// Icon has no color plane, image data stored in mask
const int nWrittenBytes = GetObject(info.hbmMask, sizeof(bmp), &bmp);
if(nWrittenBytes > 0)
myinfo.nWidth = bmp.bmWidth;
myinfo.nHeight = bmp.bmHeight / 2;
myinfo.nBitsPerPixel = 1;
if(info.hbmColor)
DeleteObject(info.hbmColor);
if(info.hbmMask)
DeleteObject(info.hbmMask);
return myinfo;
【讨论】:
【参考方案2】:Win32 GetIconInfo
调用将作为其响应的一部分返回图标的源位图。您可以从中获取图标图像大小。
Dim IconInf As IconInfo
Dim BMInf As Bitmap
If (GetIconInfo(hIcon, IconInf)) Then
If (IconInf.hbmColor) Then ' Icon has colour plane
If (GetObject(IconInf.hbmColor, Len(BMInf), BMInf)) Then
Width = BMInf.bmWidth
Height = BMInf.bmHeight
BitDepth = BMInf.bmBitsPixel
End If
Call DeleteObject(IconInf.hbmColor)
Else ' Icon has no colour plane, image data stored in mask
If (GetObject(IconInf.hbmMask, Len(BMInf), BMInf)) Then
Width = BMInf.bmWidth
Height = BMInf.bmHeight \ 2
BitDepth = 1
End If
End If
Call DeleteObject(IconInf.hbmMask)
End If
【讨论】:
谢谢,我的彩色图标工作正常。面具案例中“Height = BMInf.bmHeight \ 2”的目的是什么? @Timbo:见 msdn:ICONINFO,单色图标在 hbmMask 中包含图像和 XOR 掩码。【参考方案3】:这里是 Python 版本的代码:
import win32gui
hIcon = some_icon
info = win32gui.GetIconInfo(hIcon)
if info:
if info[4]: # Icon has colour plane
bmp = win32gui.GetObject(info[4])
if bmp:
Width = bmp.bmWidth
Height = bmp.bmHeight
BitDepth = bmp.bmBitsPixel
else: # Icon has no colour plane, image data stored in mask
bmp = win32gui.GetObject(info[4])
if bmp:
Width = bmp.bmWidth
Height = bmp.bmHeight // 2
BitDepth = 1
info[3].close()
info[4].close()
【讨论】:
以上是关于如何从 HICON 中确定图标的大小?的主要内容,如果未能解决你的问题,请参考以下文章
从 hIcon/hBitmap 获取 bytes/char*