在C#中计算字符串的显示宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/263614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate the display width of a string in C#?
提问by Jeffrey Meyer
A Java version of this question was just answered, and, well, I don't know how to do this in .net.
刚刚回答了这个问题的 Java 版本,而且,我不知道如何在 .net 中做到这一点。
So how do you calculate the display width of a string in C# / .net?
那么在C#/.net中如何计算字符串的显示宽度呢?
采纳答案by Jon Skeet
You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.
您在这个问题中遇到了与 Java 问题中存在的问题相同的问题 - 信息不足!WinForms 和 WPF 之间会有所不同。
For WinForms: Graphics.MeasureString
对于 WinForms:Graphics.MeasureString
For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...
对于 WPF,我不确定,但我怀疑这将取决于您绘制文本的确切方式......
回答by Andrew Bullock
回答by jons911
You would use Graphics.MeasureString.
您将使用 Graphics.MeasureString。
回答by Alan
An alternative for Windows Forms is the static TextRenderer.MeasureText method.
Windows 窗体的替代方法是静态 TextRenderer.MeasureText 方法。
Although restricted to integer sizes, this (in tandem with TextRenderer.DrawText) renders more accurate and much higher quality ClearType text than the Graphics.MeasureString/DrawString duo.
尽管限制为整数大小,但与 Graphics.MeasureString/DrawString 组合相比,它(与 TextRenderer.DrawText 一起)呈现更准确、质量更高的 ClearType 文本。
回答by Todd White
In WPF you would use FormattedText.
在 WPF 中,您将使用FormattedText。
回答by Thulani Chivandikwa
Graphics.MeasureString([text to measure],[font being used to measure text]);
Graphics.MeasureString([要测量的文本],[用于测量文本的字体]);
The resulting object will provide the following:
生成的对象将提供以下内容:
Other overloads of MeasureString also available.
MeasureString 的其他重载也可用。