C# 带图形的字符串测量.MeasureString

C# 带图形的字符串测量.MeasureString,c#,graphics,measurement,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 strin

请查看我的代码:

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!
Graphics grfx=Graphics.FromImage(新位图(1,1));
System.Drawing.Font f=新的System.Drawing.Font(“Times new Roman”,10,FontStyle.Regular);
常量字符串text1=“检查空间”;
SizeF bounds1=grfx.MeasureString(文本1,f);
const string text2=“检查空间”;
SizeF bounds2=grfx.MeasureString(文本2,f);
Assert.IsTrue(bounds1.Width
我想知道为什么我的考试不及格。为什么尾部有空格的文本在宽度上不大于没有空格的文本


更新:我能理解这两个字符串并不相等。但正如我在心理上所理解的,有空格的字符串应该比没有空格的字符串的宽度更大。不要?

您必须告诉它测量尾随空格,默认情况下它不会测量尾随空格

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 ) );

它们是否有可能相等?请尝试使用
“check\u space.”
“check\u space.”
。他们不相等。我已经在下面发布了答案。我不知道你为什么不接受它…因为它必须经过一段时间-系统不允许立即接受它!萨克斯!我从未听说过这件事