如何确定给定字体的字符串的大小 [英] 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.
那么我如何知道在字体 F
中将呈现多宽的字符串 S
呢?
So how do I find out how wide string S
will be rendered in font F
?
推荐答案
这取决于所使用的渲染引擎.您基本上可以在 GDI 和 GDI+ 之间切换.可以通过设置 UseCompatibleTextRendering 来完成切换
相应的属性
It depends on the rendering engine being used. You can basically switch between GDI and GDI+. Switching can be done by setting the UseCompatibleTextRendering
property accordingly
当使用 GDI+ 时,你应该使用 MeasureString
:
When using GDI+ you should use MeasureString
:
string s = "A sample string";
SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));
当使用 GDI(即本机 Win32 渲染)时,您应该使用 TextRenderer
类:
When using GDI (i.e. the native Win32 rendering) you should use the TextRenderer
class:
SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
请参阅这篇文章:文本渲染:使用复杂脚本构建全球通用的应用程序Windows 窗体控件
这篇关于如何确定给定字体的字符串的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!