gdi +-Graphics.MeasureString太宽或太窄 [英] gdi+ - Graphics.MeasureString either too wide or too narrow

查看:86
本文介绍了gdi +-Graphics.MeasureString太宽或太窄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#中的 System.Drawing 库来测量字符串的大小:

  SizeF size = gfx.MeasureString("Hello",myFont); 

但是,这将返回一个大小,在文本周围有一些间距.这是带有红色边框的文本,该边框表示返回的 MeasureString 大小.框和文本的TopLeft角都完全相同.

我偶然发现了建议使用的Stack Overflow上的

几乎是完美的,但尺寸始终太窄,切成最后一个字母.这些结果可以用我尝试过的任何大小的字体,任何字符串和任何 width 参数进行再现.

我当前的解决方法是在绘制文本时将文本向左偏移5个像素.我想念什么?

解决方案

结果我还不得不使用 StringFormat.GenericTypographic 绘制字符串,而不仅仅是用它来衡量.新的DrawString调用看起来像这样:

  gfx.DrawString("Hello",myFont,myBrush,topLeft,StringFormat.GenericTypographic); 

I'm using the System.Drawing library in C# to measure a string's size:

SizeF size = gfx.MeasureString("Hello", myFont);

However, this returns a size with a bit of spacing around the text. Here's the text rendered with a red bounding box that represents the size MeasureString returned. The TopLeft corner of both the box and the text is exactly the same point.

I stumbled upon this question on Stack Overflow that recommended using StringFormat.GenericTypographic to remove the spacing. So I changed my code to the following:

SizeF size = gfx.MeasureString("Hello", myFont, 0, StringFormat.GenericTypographic);

Which yields the following result (again, the TopLeft corner of the box and the text is identical):

Almost perfect, but the size is consistently too narrow and cuts into the last letter. These results are reproducible with any font of any size I tried, with any string and with any width parameter.

My current workaround is to offset the text 5 pixels to the left when drawing it. What am I missing?

解决方案

Turns out I also had to draw the string using StringFormat.GenericTypographic, not just measure with it. The new DrawString call looks like this:

gfx.DrawString("Hello", myFont, myBrush, topLeft, StringFormat.GenericTypographic);

这篇关于gdi +-Graphics.MeasureString太宽或太窄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆