[英]How to determine the size of a string given a font
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 S
will be rendered in font F
? 那么如何找出字体F
字符串S
宽度?
It depends on the rendering engine being used. 这取决于正在使用的渲染引擎。 You can basically switch between GDI and GDI+. 您基本上可以在GDI和GDI +之间切换。 Switching can be done by setting the UseCompatibleTextRendering
property accordingly 可以通过相应地设置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 (ie the native Win32 rendering) you should use the TextRenderer
class: 使用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 请参阅此文章: 文本呈现:在Windows窗体控件中使用复杂脚本构建支持全球的应用程序
回到Win32,我使用了VisualStyleRenderer :: GetTextExtent函数的等价物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.