2011-03-09 940 views
10

有沒有辦法檢測vb.net web應用程序中文本的實際寬度?它需要依賴於它的字體樣式和大小。在vb.net中檢測文本的寬度

在vb6中,您可以將文本複製到標籤中,並將其展開爲適合寬度,然而這不適用於vb.net。

+3

標籤技巧仍然有效,但它笨重和低效。 – 2011-03-09 12:57:14

+1

它總是:-) – Urbycoz 2011-03-09 13:24:38

回答

22

更新:在進一步的檢查,TextRenderer.MeasureText似乎是一個更好的選擇:

Dim text1 As String = "Measure this text" 
    Dim arialBold As New Font("Arial", 12.0F) 
    Dim textSize As Size = TextRenderer.MeasureText(text1, arialBold) 

Graphics.MeasureString

措施指定的字符串時 用指定的字體繪製。

Dim myFontBold As New Font("Microsoft Sans Serif", 10, FontStyle.Bold) 
    Dim StringSize As New SizeF 

    StringSize = e.Graphics.MeasureString("How wide is this string?", myFontBold) 
+0

謝謝。這絕對是那種事情。唯一的麻煩是它似乎需要PaintEventArgs「e」。 – Urbycoz 2011-03-09 12:46:35

+0

如果我使用創建圖形對象並使用它,我不需要paintEventArgs e。即Dim g As Graphics = Graphics.FromImage(New Bitmap(1,1)) – Urbycoz 2011-03-09 12:53:34

+1

似乎TextRenderer只能在Windows應用程序中使用,而不能在web應用程序中使用。儘管知道有用。乾杯。 – Urbycoz 2011-03-09 13:01:48