Monday, August 15, 2011

Get the Exact Width of A String Using MeasureCharacterRanges

Getting the exact size of a string will not always work using MeasureString. Here is the remark coming the MSDN website:

The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString.

So to obtain the actual size, MSDN continues:
"...To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRangesmethod or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.

Here is the code on how to obtain the exact size using MeasureCharacterRanges:

Public Function MeasureDisplayStringWidth(ByVal dGraphics As Graphics, ByVal dText As String, ByVal dFont As Font) As Integer	
	Dim dRect As New System.Drawing.RectangleF(0, 0, Integer.MaxValue, Integer.MaxValue)
    Dim dRange As System.Drawing.CharacterRange() = {New System.Drawing.CharacterRange(0, dText.Length)}
    Dim dRegion As System.Drawing.Region() = New System.Drawing.Region(0) {}
    Dim dFormat As New System.Drawing.StringFormat()

    dFormat.SetMeasurableCharacterRanges(dRange)

    dRegion = dGraphics.MeasureCharacterRanges(dText, dFont, dRect, dFormat)
    dRect = dRegion(0).GetBounds(dGraphics)
	Return CInt(Math.Truncate(dRect.Right + 1))
End Function