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

删除回忆录丶 提交于 2021-02-10 14:34:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!