开发者

Detect width of text in vb.net

Is there a way to detect the actual width of text in a vb.net web app? It needs to be dependant upon its font-style and size.

In vb6 you could c开发者_StackOverflow社区opy the text into a label and make it expand to fit then measure its width, but this won't work in vb.net.


Update: On further inspection, TextRenderer.MeasureText seems a better option:

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

See Graphics.MeasureString:

Measures the specified string when drawn with the specified Font.

    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)


i have just recently done this in one of my projects here is how i did it

Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
        cbx_Email.Width = textsize.Width + 17

this is in a combobox.SelectedIndex changed sub.

The +17 is for the pixels that the dropdown arrow takes up in a combobox so it doesntcover text.

by using control.font it allows the code to dynamically change no matter what font is being used. Using Control.Text means you can use this on anything and wont have to change the code when changing the text of the control or page.


I wrote this low-end function to do just that without higher-level API's.

It creates a bitmap and graphics object, writes the string to the bitmap, scans backwards for the font edge and then returns the width in pixels

   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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜