MeasureString() pads the text on the left and the right

自作多情 提交于 2019-11-30 17:35:20
HitScan

It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.

MSDN suggests using a different method if you need more accuracy:

To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.

It's true that is by design, however the link on the accepted answer is actually not perfect. The issue is the use of floats in all those methods when what you really want to be using is pixels (ints).

The TextRenderer class is meant for this purpose and works with the true sizes. See this link from msdn for a walkthrough of using this.

vscpp

Append StringFormat.GenericTypographic will fix your issue:

graphics->MeasureString(L"PP", 1, font, width, StringFormat.GenericTypographic);

Apply the same attribute to DrawString.

Sounds like it might also be connecting to hinting, based on this kb article, Why text appears different when drawn with GDIPlus versus GDI

TextRenderer was great for getting the size of the font. But in the drawing loop, using TextRenderer.DrawText was excruciatingly slow compared to graphics.DrawString().

Since the width of a string is the problem, your much better off using a combination of TextRenderer.MeasureText and graphics.DrawString..

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