Bip901
Bip901

Reputation: 808

gdi+ - Graphics.MeasureString either too wide or too narrow

I'm using the System.Drawing library in C# to measure a string's size:

SizeF size = gfx.MeasureString("Hello", myFont);

However, this returns a size with a bit of spacing around the text. Here's the text rendered with a red bounding box that represents the size MeasureString returned. The TopLeft corner of both the box and the text is exactly the same point.

Hello with a spacious bounding box

I stumbled upon this question on Stack Overflow that recommended using StringFormat.GenericTypographic to remove the spacing. So I changed my code to the following:

SizeF size = gfx.MeasureString("Hello", myFont, 0, StringFormat.GenericTypographic);

Which yields the following result (again, the TopLeft corner of the box and the text is identical):

Hello without spacing but the bounding box cuts into the text

Almost perfect, but the size is consistently too narrow and cuts into the last letter. These results are reproducible with any font of any size I tried, with any string and with any width parameter.

My current workaround is to offset the text 5 pixels to the left when drawing it. What am I missing?

Upvotes: 5

Views: 1056

Answers (1)

Bip901
Bip901

Reputation: 808

Turns out I also had to draw the string using StringFormat.GenericTypographic, not just measure with it. The new DrawString call looks like this:

gfx.DrawString("Hello", myFont, myBrush, topLeft, StringFormat.GenericTypographic);

Upvotes: 2

Related Questions