【问题标题】:String measurement with Graphics.MeasureString使用 Graphics.MeasureString 进行字符串测量
【发布时间】:2012-03-27 19:38:46
【问题描述】:

请看我的代码:

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!

我想知道为什么我的测试失败了。为什么文本with尾部空格比文本没有空格宽?

更新:我可以理解这两个字符串不相等。但据我所知,字符串 with 空间的宽度应大于字符串 without 空间。不要?

【问题讨论】:

  • 他们是平等的吗?
  • 试试"check_space.""check_space ."。它们不相等。
  • 我已经在下面发布了答案。我不知道你为什么不接受它......
  • 因为它必须经过一段时间-系统不允许立即接受它

标签: c# graphics measurement


【解决方案1】:

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

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

【讨论】:

  • 哇!谢谢!我从来没有听说过这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2021-09-06
  • 2014-11-08
  • 2012-04-29
相关资源
最近更新 更多