Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
StringFormat f = new StringFormat(StringFormat.GenericTypographic)
                     { FormatFlags = StringFormatFlags.MeasureTrailingSpaces };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...