在VB.NET中检测文本的宽度

12

有没有一种方法可以在vb.net Web应用程序中检测文本的实际宽度?它需要依赖于其字体样式和大小。

在vb6中,您可以将文本复制到标签中并使其自适应以测量其宽度,但在vb.net中无法使用此方法。


3
标签技巧仍然有效,但它不够流畅高效。 - Konrad Rudolph
3个回答

30

更新: 经进一步检查,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)

谢谢。这绝对是需要的东西。唯一的问题是似乎需要PaintEventArgs“e”。 - Urbycoz
如果我使用创建图形对象并使用它,我就不需要paintEventArgs e。即Dim g As Graphics = Graphics.FromImage(New Bitmap(1, 1))。 - Urbycoz
1
似乎 TextRenderer 只能在 Windows 应用程序中使用,而不能在 Web 应用程序中使用。虽然这一点很有用,但需要注意。谢谢。 - Urbycoz
1
附加示例(Winforms)- 增加文本框的宽度:Dim textSize As System.Drawing.Size = TextRenderer.MeasureText(txtField1.Text, txtField1.Font) .. txtField1.Width = textSize.Width + 16 - AjV Jsy

1
我最近在一个项目中刚刚做过这个,以下是我的做法。
Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
        cbx_Email.Width = textsize.Width + 17

这是在ComboBox的SelectedIndexChanged子程序中。+17是为了防止下拉箭头遮盖文本而加上的像素值。
使用Control.Font可以动态更改代码,无论使用什么字体。使用Control.Text意味着您可以在任何控件或页面上使用它,而不必在更改控件或页面文本时更改代码。

0

我编写了这个低端函数,以此来实现没有高级API的功能。

它创建了一个位图和图形对象,将字符串写入位图,向后扫描字体边缘,然后返回像素宽度。

   Private Function FontLengthInPixels(inputString As String, FontStyle As Font) As Integer

    ' Pick a large, arbitrary number for the width (500) in my case
    Dim bmap As New Bitmap(500, 100)
    Dim g As Graphics = Graphics.FromImage(bmap)
    g.FillRectangle(Brushes.Black, bmap.GetBounds(GraphicsUnit.Pixel))
    g.DrawString(inputString, FontStyle, Brushes.White, New Point(0, 0))


    ' Scan backwards to forwards, since we know the first pixel location is 0,0; we need to find the LAST and subtract
    ' the bitmap width from it to find the width.
    For x = -(bmap.Width - 1) To -1

        ' Scan from the 5th pixel to the 10th, we'll find something within that range!
        For y = 5 To 10

            Dim col As Color = bmap.GetPixel(Math.Abs(x), y)

            ' Look for white (ignore alpha)
            If col.R = 255 And col.G = 255 And col.B = 255 Then
                Return Math.Abs(x) ' We got it!
            End If
        Next
    Next

    ' Lets do this approx
    Return 0
End Function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接