有没有办法在vb.net网络应用中检测文本的实际宽度?它需要依赖于它的字体样式和大小。
在vb6中,您可以将文本复制到标签中并使其展开以适合然后测量其宽度,但这在vb.net中不起作用。
答案 0 :(得分:25)
更新:进一步检查后,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)
何时测量指定的字符串 使用指定的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)
答案 1 :(得分: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
答案 2 :(得分:0)
我最近在我的一个项目中完成了此操作,这是我的操作方式
Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
cbx_Email.Width = textsize.Width + 17
这是在组合框中。
+17代表下拉箭头在组合框中占据的像素,因此它不会覆盖文本。
通过使用control.font,无论使用什么字体,它都允许代码动态更改。使用Control.Text意味着您可以在任何对象上使用它,并且在更改控件或页面的文本时不必更改代码。