请看我的代码:
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(new Bitmap(1,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,new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );