当然,众所周知,Graphics.MeasureString方法存在填充问题,因此您使用Graphics.MeasureCharacterRanges,但正如您在此处所见:
测量不正确。这是MeasureCharacterRanges的问题还是我的代码?我该如何解决?
这是我的代码:
'Draw the selection cursor
If Me.Focused Then
Dim cX As Integer = 1, cY As Integer = 5, c As Char
For i As Integer = 0 To Me.SelectionStart - 1
c = Me.Text(i)
If c = ControlChars.CrLf Then
cY += Me.Font.Height
Else
Dim w As Integer = MeasureCharacter(g, c, Me.Font).Width
g.DrawRectangle(Pens.Black, cX, cY, w, Me.Font.Height) 'Draw a rectangle for debugging
cX += w
End If
Next
g.DrawLine(Pens.Black, cX, cY, cX, cY + Me.Font.Height)
End If
End Sub
Protected Function MeasureCharacter(ByVal g As Graphics, ByVal c As Char, ByVal f As Font) As Size
Dim cr() As CharacterRange = {New CharacterRange(0, 1)}
Dim sfmt As New StringFormat()
sfmt.FormatFlags = StringFormatFlags.MeasureTrailingSpaces
sfmt.SetMeasurableCharacterRanges(cr)
Return g.MeasureCharacterRanges(c.ToString(), f, Me.ClientRectangle, sfmt)(0).GetBounds(g).Size.ToSize()
End Function
答案 0 :(得分:3)
测量单个字符的长度不考虑字符组之间出现的字距,因此字符长度的总和不等于字符串的长度。
如果你查看你的示例文本,你可以看到“Sprint”结尾处的“t”和“Textbox”开头的“T”之间的字距,字符比你想要的更接近。期待各自的长度。