分析
計算某串文本在繪制UI上需要占用的寬度,需要以下幾個要素:
- 字符串本身
- 所使用的字體
字體會影響所繪制的文字的寬度——那是理所當然的 - 所使用的GDI或GDI+對象
方法
GDI
::SelectObject(hDC, hFont);
//第四個參數:指向SIZE結構的指針,該結構中字符串的尺寸將被返回。
::GetTextExtentPoint32(hDC, str, StrLen(str), &sizeText);
GDI+
- 比GDI復雜,需要使用到GDI+對象的API
MeasureString
Gdiplus::RectF rc1(0, 0, 5000, 2000);
Gdiplus::RectF rc2(0, 0, 0, 0);
g.MeasureString(str, -1, pFont, rc1, pStrFormat, &rc2);
return rc2.Width;
- 其中參數4是
Gdiplus::StringFormat
,類似的賦值方式如下:
Gdiplus::StringFormat* pStrFormat = new Gdiplus::StringFormat();
pStrFormat->SetAlignment(enHAlign);
pStrFormat->SetLineAlignment(enVAlign);
If_Do(nFormat != 0, pStrFormat->SetFormatFlags(nFormat));
-
可以參考MSDN上的StringAlignment Enumeration,和StringFormatFlags Enumeration。
-
舉例:
SetFormatFlags
傳入參數StringFormatFlagsNoWrap
則禁用換行,否則在矩形內繪制文本時是自動換行的。 -
還可以使用
SetTextRenderingHint
API設置文本的渲染模式,可參考MSDN中關於TextRenderingHint Enumeration的資料,一般情況下使用默認的TextRenderingHintSystemDefault
即可