假设我在 Arial Regular 中使用 14 号字体将字符“A”渲染到屏幕上。在 C# 中有没有一种方法可以计算它有多少像素宽?
我呈现文本的方式是通过 ESRI 的 ArcEngine,它通过 DynamicDisplay 引擎调用 GDI 或 GDI+(我不知道是哪个)。
最佳答案
这取决于所使用的渲染引擎。 .NET 可以使用 GDI 或 GDI+。可以通过设置 <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.label.usecompatibletextrendering.aspx" rel="noreferrer noopener nofollow">UseCompatibleTextRendering</a>
来完成切换相应地属性(property)或调用 Application.SetCompatibleTextRenderingDefault
方法。
当使用 GDI+ 时,你应该使用 MeasureString
:
string s = "A sample string";
SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));
使用 GDI(即 native Win32 渲染)时,您应该使用 TextRenderer
类:
SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
本文中描述了更多细节:
Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls
请注意,上面讨论的是 Windows 窗体。在 WPF 中,您将使用 FormattedText
关于c# - 确定渲染字符在 .NET 中的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4219798/