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

后端 未结 5 791
野趣味
野趣味 2021-01-04 01:54

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

相关标签:
5条回答
  • 2021-01-04 02:02

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

    0 讨论(0)
  • 2021-01-04 02:03

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

    0 讨论(0)
  • 2021-01-04 02:09

    Append StringFormat.GenericTypographic will fix your issue:

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

    Apply the same attribute to DrawString.

    0 讨论(0)
  • 2021-01-04 02:18

    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.

    0 讨论(0)
  • 2021-01-04 02:28

    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.

    0 讨论(0)
提交回复
热议问题