简体   繁体   English

如何确定给定字体的字符串的大小

[英]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窗体控件中使用复杂脚本构建支持全球的应用程序

How about this: 这个怎么样:

Size stringsize = graphics.MeasureString("hello", myFont);

( Here is the MSDN link.) 是MSDN链接。)

回到Win32,我使用了VisualStyleRenderer :: GetTextExtent函数的等价物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定字符串的大小,并压缩它 - How to determine size of string, and compress it 如何确定给定字体的最大高度(以像素为单位)? - How do I determine the maximum height in pixels of a given font? 如何计算给定字体和大小的页面中可以容纳的字符数 - How to calculate the number of characters that can be accommodated in a page of a given font and size 如何测量给定字体/大小(C#)中数字的像素宽度 - How to measure the pixel width of a digit in a given font / size (C#) 如何确定数组中哪个字符串与给定字符串最相似? - How to determine which string in an array is most similar to a given string? XNA-如何确定已编译的XNB文件中使用的字体类型和字体大小 - XNA - how to determine font type and font size used in compiled XNB file 如何确定字符串是否可以使用给定的编码表示 - How to determine if a string can be represented using a given encoding 确定给定的字符串是否为XML - Determine whether a given string is XML or not 如何确定给定固定宽度字体和最大宽度(以像素为单位)的最大字符数 - How to determine maximum number of characters given a fixed width font and a maximum width in pixels 确定给定空间中图像的最佳尺寸 - Determine best size for images in an given space
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM