使用Graphics.MeasureString进行字符串测量

时间:2012-03-27 19:38:46

标签: c# graphics measurement

请参阅我的代码:

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1));

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular);

const string text1 = "check_space";
SizeF bounds1 = grfx.MeasureString(text1, f);

const string text2 = "check_space ";
SizeF bounds2 = grfx.MeasureString(text2, f);

Assert.IsTrue(bounds1.Width < bounds2.Width); // I have Fail here!

我想知道为什么我的测试失败了。为什么空格的尾部 NOT 宽度大于文字没有空格?

更新:我可以理解这两个字符串不相等。但是,当我在心理上理解字符串空格时,宽度应该大于字符串没有空格。不要?

1 个答案:

答案 0 :(得分:12)

你必须告诉它测量尾随空格,默认情况下不会这样做。

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1));

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular);

string text1 = "check_space";
SizeF bounds1 = grfx.MeasureString(text1, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ));

string text2 = "check_space ";
SizeF bounds2 = grfx.MeasureString(text2, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );