C# - TextRenderer.MeasureText is a few pixels too wide

隐身守侯 提交于 2020-12-16 06:27:40

问题


I'm using TextRendere.MeasureText instead of Graphics.MeasureString because it allows me to specify TextFormatFlags.NoPadding, but its return width is a few pixels to wide. For a four character text string its five pixels over and for a five character text string its six pixels over. I'm sure its going to be even more with longer text strings. I'm using .Net 4.5.1. Here's my code:

Size size = TextRenderer.MeasureText(items[a], new Font("Segoe UI", 12, GraphicsUnit.Pixel), new Size(Width, 15), TextFormatFlags.NoPadding);

How do I get the exact (+- 1/2px is ok) text width? Thanks :D


回答1:


Contrary to popular believe Graphics.MeasureString is the better choice to measure short strings without getting extra space.

You need to use the StringFormat GenericTypographic:

SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(items[a], 
                                      new Font("Segoe UI", 12, GraphicsUnit.Pixel), 
                                      new SizeF(Width, 15f), 
                                      StringFormat.GenericTypographic);

Here is a quote from MSDN :

The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString. To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.

I would also suggest using SizeF if you plan to add up sizes.



来源:https://stackoverflow.com/questions/26360757/c-sharp-textrenderer-measuretext-is-a-few-pixels-too-wide

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