1

当然,众所周知,Graphics.MeasureString 方法存在填充问题,因此您可以改用 Graphics.MeasureCharacterRanges,但正如您在此处看到的:

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
4

1 回答 1

3

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

如果您查看示例文本,您可以看到“Sprint”末尾的“t”和“Textbox”开头的“T”之间的字距调整,字符移动的距离比您预期的更近,因为它们个人长度。

于 2011-05-18T03:25:35.077 回答