2009-07-14 77 views

回答

20

嘗試使用GetTextExtentPoint32。它使用給定設備上下文的當前字體以邏輯單位測量渲染字符串的寬度和高度。對於默認映射模式MM_TEXT,1個邏輯單元爲1個像素。

但是,如果您更改了當前設備上下文的映射模式,則邏輯單元可能與像素不同。您可以閱讀有關不同的mapping modes on MSDN。使用映射模式,您可以將由GetTextExtentPoint32返回給您的維度轉換爲像素。

+0

謝謝,這就是我所喜歡的。 :) – Razvi 2009-07-14 17:38:28

3

Graphics::MeasureString

VOID Example_MeasureString(HDC hdc) 
{ 
    Graphics graphics(hdc); 
    // Set up the string. 
    WCHAR string[] = L"Measure Text"; 
    Font font(L"Arial", 16); 
    RectF layoutRect(0, 0, 100, 50); 
    RectF boundRect; 
    // Measure the string. 
    graphics.MeasureString(string, 12, &font, layoutRect, &boundRect); 
    // Draw a rectangle that represents the size of the string. 
    graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect); 
}
+0

你的方法肯定比使用GetTextExtentPoint32()更好。 – 2015-10-31 05:24:12

+0

我有一個困惑的事情。 layoutRect是什麼?我不明白 – Kross 2016-08-02 07:44:05

1

取決於你如何使用它,你可以使用DrawText和DT_CALCRECT指定的,它會(它總是對我來說相當準確)根據文本/字體等計算所需矩形的大小。

13

我不知道某些,但似乎:

HDC hDC = GetDC(NULL); 
RECT r = { 0, 0, 0, 0 }; 
char str[] = "Whatever"; 
DrawText(hDC, str, strlen(str), &r, DT_CALCRECT); 

可能會奏效。

0

對於Builder C++首先動態創建新的TLabel,然後更改字體屬性。將您的TLabel設置爲autosize。然後您可以得到TLabel width witch表示您的字符串寬度(以像素爲單位)。

int WidthPixels (String font, int size, String text) 
{ 
    TLabel* label = new TLabel(Form1); // dynamic TLabel 
    label->AutoSize = true; 
    label->Font->Name = font; // your font 
    label->Font->Size = size; // your font size 
    label->Caption = text; // your string 
    return label->Width; 
} 

int width = WidthPixels("Times New Roman", 19 , "Hey"); 
相關問題