2011-03-09 41 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