user1476997
user1476997

Reputation: 41

GDI+ MeasureString() is incorrectly trimming text

I am trying to complete a code that can layout text on the screen. The following C# code placed in the Paint event handler of an otherwise empty Windows Form is an example:

string[] s = new string[] { "Sample text ", "to test", " this layout ", "algorithm" };
PointF[] pts = new PointF[s.Length];
PointF start = new PointF(10, 10);
StringFormat f = new StringFormat(StringFormat.GenericTypographic);
float x = start.X;
float y = start.Y;
for (int i = 0; i < pts.Length; i++)
{
    pts[i] = new PointF(x, y);
    SizeF sz = e.Graphics.MeasureString(s[i], Font, pts[i], f);
    x += sz.Width;
    e.Graphics.DrawString(s[i], Font, Brushes.Black, pts[i]);
}

It works correctly except for trimming the whitespace before and after each piece of text in the s array. It should display like this:

Sample text to test this layout algorithm

But instead it appears like this:

Sample textto testthis layoutalgorithm

I have confirmed that the f.Trimming property is set to None. I would have guessed that this would add trailing and opening whitespace to the measure of the strings, but it still trims it. Any ideas about how to make the MeasureString method include the whitespace? The kerning otherwise is handled perfectly.

Upvotes: 4

Views: 2975

Answers (1)

GSerg
GSerg

Reputation: 78190

StringFormat f = new StringFormat(StringFormat.GenericTypographic)
                     { FormatFlags = StringFormatFlags.MeasureTrailingSpaces };

Upvotes: 15

Related Questions