C# 如何确定给定字体的字符串的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/721168/
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
How to determine the size of a string given a font
提问by Nifle
I have a small form that displays some progress information.
Very rarely I have to show a rather long message and I want to be able to resize this form when needed so that this message fits in the form.
我有一个显示一些进度信息的小表格。
我很少需要显示相当长的消息,我希望能够在需要时调整此表单的大小,以便此消息适合表单。
So how do I find out how wide string Swill be rendered in font F?
那么我如何找出S字体中将呈现多宽的字符串F呢?
采纳答案by Dirk Vollmar
It depends on the rendering engine being used. You can basically switch between GDI and GDI+. Switching can be done by setting the UseCompatibleTextRenderingproperty accordingly
这取决于所使用的渲染引擎。您基本上可以在 GDI 和 GDI+ 之间切换。可以通过相应地设置UseCompatibleTextRendering属性来完成切换
When using GDI+ you should use MeasureString:
使用 GDI+ 时,您应该使用MeasureString:
string s = "A sample string";
SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));
When using GDI (i.e. the native Win32 rendering) you should use the TextRendererclass:
使用 GDI(即本机 Win32 渲染)时,您应该使用TextRenderer该类:
SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
See this article: Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls
回答by Frederick The Fool
回答by bernhardrusch
Back in the Win32 I was using the equivalent for VisualStyleRenderer::GetTextExtent function for this.
回到 Win32,我为此使用了 VisualStyleRenderer::GetTextExtent 函数的等效项。

