有没有一种方法可以在vb.net Web应用程序中检测文本的实际宽度?它需要依赖于其字体样式和大小。
在vb6中,您可以将文本复制到标签中并使其自适应以测量其宽度,但在vb.net中无法使用此方法。
有没有一种方法可以在vb.net Web应用程序中检测文本的实际宽度?它需要依赖于其字体样式和大小。
在vb6中,您可以将文本复制到标签中并使其自适应以测量其宽度,但在vb.net中无法使用此方法。
更新: 经进一步检查,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)
测量使用指定的字体绘制指定字符串时所需的大小。
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)
Dim textSize As System.Drawing.Size = TextRenderer.MeasureText(txtField1.Text, txtField1.Font)
.. txtField1.Width = textSize.Width + 16
- AjV JsyDim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
cbx_Email.Width = textsize.Width + 17
我编写了这个低端函数,以此来实现没有高级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