Vb.net 测量字符范围甚至不精确?

Vb.net 测量字符范围甚至不精确?,vb.net,graphics,text,measure,Vb.net,Graphics,Text,Measure,当然,众所周知,Graphics.MeasureString方法存在填充问题,因此您可以使用Graphics.MeasureCharacterRanges,但正如您在此处看到的: 它的测量不太准确。这是MeasureCharacterRanges的问题还是我的代码?我怎样才能修好它 这是我的密码: 'Draw the selection cursor If Me.Focused Then Dim cX As Integer = 1, cY As Integer

当然,众所周知,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

测量单个字符的长度不考虑字符组之间发生的字距调整,因此字符长度之和不等于字符串的长度


如果您查看示例文本,您可以看到“Sprint”结尾的“t”和“Textbox”开头的“t”之间的紧排,字符移动的距离比您预期的要近,这取决于您尝试执行的操作。如果您只需要字符串的长度,那么可以在字符串上使用MeasureCharacterRanges,这将考虑到字距调整。不,我需要(或者更愿意)出于各种原因测量每个字符。您可以通过测量字符对并从单个字符长度的总和中减去字符对来确定字符的紧排宽度,但这不会考虑在单词边界上发生的文本范围紧排,如上面的示例所示。你可以通过对单词对做同样的计算来解决这个问题。