Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate font height in WPF?

Tags:

For a FontFamily how do I programatically retrieve/calculate the maximum height range for that font at a particular FontSize?

I need a value to set the height of a textblock that will display the font at the specified FontSize - this has to be carried out programatically.

I need a value that will take into consideration ascenders and descenders, etc.

Update

To clarify, I need the maximum height range for the entire FontFamily, not the height of some sample text in that font. I do not know what the text will be in advance.

like image 808
Tim Lloyd Avatar asked Dec 22 '10 13:12

Tim Lloyd


2 Answers

The maximum height range for a font can be calculated using its LineSpacing property which is a proportional figure for the font. This can be used to give a line height which can accommodate all glyphs for that font at a particular size.

    FontFamily fontFamily = new FontFamily("Segoe UI");     double fontDpiSize = 16;      double fontHeight = Math.Ceiling(fontDpiSize * fontFamily.LineSpacing); 

Result:

   22.0 

This figure will contain a small amount of leading which is desirable when needing a height for rows of text (so that ascenders and descenders from adjacent rows of text have spacing).

enter image description here

like image 193
Tim Lloyd Avatar answered Oct 22 '22 05:10

Tim Lloyd


Use System.Windows.Media.FormattedText class.

Example:

FormattedText ft = new FormattedText("Quick Brown Fox Jumps Over A Lazy Dog.",                                      CultureInfo.CurrentCulture,                                      CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight,                                      new Typeface("Verdana"),                                      9,                                      new SolidColorBrush(Colors.White) Double maxHeight = ft.MaxTextHeight; 
like image 26
decyclone Avatar answered Oct 22 '22 04:10

decyclone