C#-TextRenderer.MeasureText太宽了几个像素 [英] C# - TextRenderer.MeasureText is a few pixels too wide

查看:166
本文介绍了C#-TextRenderer.MeasureText太宽了几个像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是TextRendere.MeasureText而不是Graphics.MeasureString,因为它允许我指定TextFormatFlags.NoPadding,但其返回宽度为几像素宽.对于四个字符的文本字符串,其五个像素以上;对于五个字符的文本字符串,其六个像素以上.我敢肯定,更长的文本字符串会更加有效.我正在使用.Net 4.5.1.这是我的代码:

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

如何获得准确的(+-1/2px的)文本宽度?谢谢:D

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

推荐答案

与流行的看法相反, Graphics.MeasureString 是在不占用额外空间的情况下测量短字符串的更好选择.

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

您需要使用 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);

这是来自 MSDN 的报价a>:

MeasureString方法设计用于单个字符串并且在字符串前后包含少量的额外空间允许悬空的字形.另外,DrawString方法会调整字形点可优化显示质量,并可能显示字符串小于MeasureString报告的范围.获得合适的指标用于布局中的相邻字符串(例如,实现时格式的文本),请使用MeasureCharacterRanges方法或其中一种带有StringFormat并通过的MeasureString方法通用印刷.另外,请确保TextRenderingHint图形是AntiAlias.

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.

如果您打算增加尺寸,我也建议使用SizeF.

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

这篇关于C#-TextRenderer.MeasureText太宽了几个像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆