在vb.net中检测文本宽度

在vb.net中检测文本宽度,vb.net,Vb.net,有没有办法检测vb.net web应用程序中文本的实际宽度?它需要依赖于它的字体样式和大小 在vb6中,您可以将文本复制到标签中,使其展开以适合,然后测量其宽度,但这在vb.net中不起作用。更新:进一步检查后,这似乎是一个更好的选择: Dim text1 As String = "Measure this text" Dim arialBold As New Font("Arial", 12.0F) Dim textSize As Size = TextRenderer

有没有办法检测vb.net web应用程序中文本的实际宽度?它需要依赖于它的字体样式和大小


在vb6中,您可以将文本复制到标签中,使其展开以适合,然后测量其宽度,但这在vb.net中不起作用。

更新:进一步检查后,这似乎是一个更好的选择:

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

在以下情况下测量指定的字符串: 用指定的字体绘制


我编写这个低端函数就是为了在没有高级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

我最近在我的一个项目中做了这件事,我就是这样做的

Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
        cbx_Email.Width = textsize.Width + 17
这在一个组合框中。SelectedIndex changed sub

+17表示下拉箭头在组合框中占据的像素,因此它不会覆盖文本


通过使用control.font,无论使用何种字体,它都允许代码动态更改。使用Control.Text意味着您可以在任何情况下使用它,并且在更改控件或页面的文本时不必更改代码。

谢谢。这绝对是一种事情。唯一的问题是它似乎需要PaintEventArgs“e”。如果我使用CreateGraphicsObject并使用它,我就不需要PaintEventArgs“e”。i、 例如,Dim g As Graphics=Graphics.FromImage(新位图(1,1))似乎只能在windows应用程序中使用,而不能在web应用程序中使用。不过,了解这一点很有用。干杯。其他示例(Winforms)-增加文本框的宽度:
Dim textSize As System.Drawing.Size=TextRenderer.MeasureText(txtField1.Text,txtField1.Font)
txtField1.Width=textSize.Width+16
标签技巧仍然有效,但它笨重且效率低下。
Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
        cbx_Email.Width = textsize.Width + 17