问题
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.
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):
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?
回答1:
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);
来源:https://stackoverflow.com/questions/65559919/gdi-graphics-measurestring-either-too-wide-or-too-narrow