Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 216
Tim Cooper Avatar asked Sep 23 '08 01:09

Tim Cooper


1 Answers

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.

like image 117
HitScan Avatar answered Sep 18 '22 04:09

HitScan