加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:29:13 所属栏目:百科 来源:网络整理
导读:请看我的代码: 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
请看我的代码:
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 ) );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读