Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c# - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...