至此,所有我們需要的信息都獲取到了,並進行了必要的清除工作。在CFontComboBox頭文件裏還有兩個函數沒有介紹:MeasureItem、DrawItem.。熟悉MFC控件類的朋友一看就知道是自繪控件。接下來我們就看看自繪是如何進行的。在自繪CListCtrl、CListBox、CComboBox時,都需要重載MeasureItem、DrawItem函數,前者計算每個Item需要的高度,後者完成繪圖功能。
void CFontComboBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
int height;
CWindowDC dc(NULL);
TEXTMETRIC tm;
dc.GetTextMetrics(&tm);
height = tm.tmHeight - tm.tmInternalLeading;
lpMeasureItemStruct->itemHeight = height - 1;
}
在DrawItem完成繪圖時,需要根據字體類型和圖像類型畫上不同的圖像。函數的參數DRAWITEMSTRUCT結構裏有我們需要的信息:
CtlType: 控件的類型
itemID: 當前繪圖Item索引ID值
hDC: 當前繪圖Item的畫圖DC
itemAction: 當前繪圖Item的狀態(焦點、選擇)
rcItem: 當前繪圖Item的矩形大小
void CFontComboBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
ASSERT(lpDrawItemStruct->CtlType == ODT_COMBOBOX);
CString strText;
//判斷當前索引的字體名稱是否爲空
int nIndex = lpDrawItemStruct->itemID;
if (GetLBTextLen(nIndex) < 0)
return ;
GetLBText(nIndex, strText);
ASSERT(!strText.IsEmpty());
int nImage = 0;
//根據索引值從m_pFontVec得到字體圖像類型
if (!m_pFontVec.empty())
nImage = m_pFontVec[nIndex]->GetImage();
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
COLORREF crOldTextColor = dc.GetTextColor();
COLORREF crOldBkColor = dc.GetBkColor();
//如果Item處於選擇焦點、狀態下,用系統高亮色改變文本和背景色
if ((lpDrawItemStruct->itemAction | ODA_SELECT) &&
(lpDrawItemStruct->itemState & ODS_SELECTED))
{
dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
dc.SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
dc.FillSolidRect(&lpDrawItemStruct->rcItem, ::GetSysColor(COLOR_HIGHLIGHT));
}
else
dc.FillSolidRect(&lpDrawItemStruct->rcItem, crOldBkColor);
CRect rItem(lpDrawItemStruct->rcItem);
CRect rText(rItem);
CRect rBmp(&rItem);
if(m_FontBmp)
{
//計算Item中字體預覽圖的貼圖位置
rBmp.top += (rBmp.Height() - FNTIMG_Y) / 2;
rBmp.bottom = rBmp.top + FNTIMG_Y + 1;
rText.left += FNTIMG_X;
if (nImage != (int)0XFF)
{
int x,y;
x = nImage * FNTIMG_X; //根據預覽圖類型計算源圖的矩形大小
y = FNTIMG_Y;
CDC mdc;
mdc.CreateCompatibleDC(&dc);
CBitmap* pOldBmp = mdc.SelectObject(CBitmap::FromHandle(m_FontBmp));
COLORREF clrTransparent = mdc.GetPixel(0, y);
//調用TransparentBlt進行透明貼圖,此函數需要加入MsImg32.Lib文件
::TransparentBlt (dc.GetSafeHdc(),rBmp.left, rBmp.top, FNTIMG_X, FNTIMG_Y,
mdc, x, y, FNTIMG_X, FNTIMG_Y, clrTransparent);
}
}
else
rText.left += 10;
//rText所代表的字體名稱填充位置需要右移圖片的寬度
dc.DrawText(strText, rText, DT_LEFT|DT_SINGLELINE|DT_VCENTER);
dc.SetTextColor(crOldTextColor);
dc.SetBkColor(crOldBkColor);
dc.Detach();
}