Determine how wide a rendered character is in .NET
Lets say I render the charact开发者_运维技巧er "A" to the screen with a size 14 font in Arial Regular. Is there a way in C# to calculate how many pixels wide it is?
The way I'm rendering text is through ESRI's ArcEngine which makes calls to GDI or GDI+ (I don't know which) in a round about fashion via the DynamicDisplay engine.
It depends on the rendering engine being used. .NET may use GDI or GDI+. Switching can be done by setting the UseCompatibleTextRendering
property accordingly or calling the Application.SetCompatibleTextRenderingDefault
method.
When using GDI+ you should use 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 TextRenderer
class:
SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
More details are described in this article:
Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls
Note that the above talks about Windows Forms. In WPF you would be using FormattedText
Here's an MSDN piece about determining font metrics. You can use Graphics.MeasureString to do the measurement.
You don’t say how you “render” it, but if you have a string, you can use MeasureString too.
Graphics.MeasureString will get you the size in the current graphics units.
Not really, you can only make an estimate. TrueType hinting, kerning and glyph overhang makes measuring individual characters next to impossible. Some code:
public float GetAWidth() {
using (var font = new Font("Arial", 14)) {
SizeF size = TextRenderer.MeasureText(new string('A', 100), font);
return size.Width / 100;
}
}
That returns 13.1 on my machine. Avoid doing this.
For windows forms you use Graphics.MeasureString, For WPF you use FormattedText.Width and FormattedText.Height.
The MeasureString property indicates how wide a field one should use to display a string, allowing some 'slop' for overhangs. In particular, the reported width of "a" plus the reported width of "b" is apt to be much greater than the reported width of "ab". As a rough approximation, I'd suggest that if you want the width of "a", you subtract the width of "||" from the width of "|a|". Note that this will still only be approximate, both because of rounding issues, and also because character widths vary with context. For example, in many fonts, the string "TATATATAT" may appear narrower than "AAAATTTTT" because the A's can nestle under the T's.
精彩评论