GDI+ MeasureString() is incorrectly trimming text

China☆狼群 提交于 2019-12-17 17:09:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11170823/gdi-measurestring-is-incorrectly-trimming-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!