windows C++如何根據文本字符串計算其繪制需占用寬度


分析

計算某串文本在繪制UI上需要占用的寬度,需要以下幾個要素:

  • 字符串本身
  • 所使用的字體
    字體會影響所繪制的文字的寬度——那是理所當然的
  • 所使用的GDI或GDI+對象

方法

GDI

::SelectObject(hDC, hFont);
//第四個參數:指向SIZE結構的指針,該結構中字符串的尺寸將被返回。
::GetTextExtentPoint32(hDC, str, StrLen(str), &sizeText); 

GDI+

  • 比GDI復雜,需要使用到GDI+對象的APIMeasureString
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));

參考鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM