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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…