Last active
December 21, 2015 13:38
-
-
Save sehrgut/6313670 to your computer and use it in GitHub Desktop.
System.Graphics#DrawString has no facilities for drawing justified text. This method will draw text into a box, justified. It only handles a single line, but TODO is wrap, so it can be a complete drop-in for Graphics#DrawString. As is, it's useful for single lines such as in logotype.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' This document is free and open-source software licensed simultaneously under the MIT License, | |
' the GPL v2, and the two-clause BSD License. | |
Public Sub DrawJustifiedString(ByRef g As Graphics, ByVal txt As String, ByVal font As Font, | |
ByVal brush As Brush, ByVal destination As RectangleF, ByVal format As StringFormat) | |
Using fmt As StringFormat = format.Clone | |
fmt.FormatFlags = fmt.FormatFlags Or StringFormatFlags.MeasureTrailingSpaces ' don't lose spaces | |
fmt.SetMeasurableCharacterRanges({New CharacterRange(0, 1)}) ' Set Graphics#MeasureCharacterRanges to measure first character | |
fmt.Alignment = StringAlignment.Center ' "Justified" is an alignment. We need to align each character Center in its computed box | |
Dim txtWidth As Double = g.MeasureString(txt, font, destination.Location, fmt).Width | |
Dim spacing As Double = (destination.Width - txtWidth) / (txt.Length - 1) | |
Dim dest As New RectangleF(destination.X, destination.Y, 0, destination.Height) | |
For Each c As Char In txt.AsEnumerable | |
' Graphics#MeasureString is too inaccurate for character placement | |
dest.Width = g.MeasureCharacterRanges(c.ToString, font, destination, fmt)(0).GetBounds(g).Width | |
g.DrawString(c.ToString, font, brush, dest, fmt) | |
dest.X += dest.Width + spacing | |
Next | |
End Using | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment