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

99封情书 提交于 2019-12-18 18:51:17

问题


I'm using GDI+ in C++. (This issue might exist in C# too).

I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.

For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".

My question is: is this intended or documented behaviour, and how do I disable this?

RectF Rect(0,0,32767,32767);
RectF Bounds1, Bounds2;
graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);
graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);
margin = Bounds1.Width * 2 - Bounds2.Width;

回答1:


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.




回答2:


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.




回答3:


Append StringFormat.GenericTypographic will fix your issue:

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

Apply the same attribute to DrawString.




回答4:


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




回答5:


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..



来源:https://stackoverflow.com/questions/118686/measurestring-pads-the-text-on-the-left-and-the-right

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