Reputation: 265
I can't figure out how the C# TextMetrics properties work. The example below, that I found somewhere and modified a bit, does something, but the result seems to be 7 no matter what font I set in the textbox.
TextMetrics metrics;
VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.TextBox.TextEdit.Normal);
using (IDeviceContext context = textBox1.CreateGraphics() as IDeviceContext)
{
metrics = renderer.GetTextMetrics(context);
}
int averageWidth = metrics.AverageCharWidth;
textBox1.Text = averageWidth.ToString(); // 7
MSDN doesn't provide any examples, and I haven't found anything comprehensible on any other web site. Could someone explain how this works?
PS: I want to use all the TextMetrics properties. Not just AverageCharWidth.
Update: I'm writing a font viewer, using private font collection. I want to get as much information about each font as I can. Then I can decide what's useful to include in the font viewer and what's not.
My font viewer reminds about Bitstream Font Navigator (http://noscope.com/2004/font-management-solution/), but I want to include more information about the fonts.
Update: I can use FontFamily methods to get some of that information, as Olivier Jacot-Descombes points out in his answer, but not all. I think I need to use TextMetrics to get information about, for example, PitchAndFamily, MaxCharWidth and AverageCharWidth. Or is there some other simple way to get this information?
Upvotes: 1
Views: 1390
Reputation: 112392
You can retrieve font metrics like this
var font = new System.Drawing.Font("Arial", 11f);
var style = System.Drawing.FontStyle.Regular;
var ff = font.FontFamily;
int ascent = ff.GetCellAscent(style);
int descent = ff.GetCellDescent(style);
int height = ff.GetEmHeight(style);
int lineSpacing = ff.GetLineSpacing(style);
float pointSize = font.SizeInPoints;
For more information see How to: Obtain Font Metrics on MSDN.
Upvotes: 2