Proper Measurement of Characters in Pixels

与世无争的帅哥 提交于 2019-12-04 18:11:33
Ian Boyd

You should not be using Graphics for any text rendering.

Starting with .NET Framework 2.0 use of Graphics.MeasureString and Graphics.DrawString was deprecated in favor of a newly added helper class TextRenderer:

  • TextRenderer.MeasureText
  • TextRenderer.DrawText

The GDI+ text renderer has been abandoned, and hasn't gotten any improvements or fixes for over 10 years; as well as being software rendered.

GDI rendering (which TextRenderer is a simple wrapper of) is hardware accelerated, and continues to get rendering improvements (ligatures, Uniscribe, etc).

Note: GDI+ text rendering is wrapped by Graphics.DrawString and MeasureString

Here's a comparison of the measure results of Graphics and TextRenderer:

The GDI+ measurements aren't "wrong", they are doing exactly what they intend - return the size that the text would be if it were rendered as the original font author intended (which you can achieve using Anti-alias rendering):

But nobody really wants to look at text the way the font designer intended, because that causes stuff to not line-up on pixel boundaries - making the text too fuzzy (i.e. as you see on a Mac). Ideally the text should be snapped to line up on actual pixel boundaries (i.e. Windows' Grid Fitting)

Bonus Reading

There's MeasureCharacterRanges that is like MeasureString, but more powerful and more accurate (and also slower).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!