0

I would like to know how to calculate the height of a given FontFamily in a Window Universal Application.

In UWP, the FontFamily object has a LineSpacing property that makes it possible to calculate the max height to allocate all the glyphs of the font, but it's not available for UWP applications.

NOTICE: About the "duplicate claim", using a TextBlock to measure the height isn't an option for me. Apart from being an ugly trick, it uses a UI object to do it. In my case, I cannot do that because I'm making a GUI Framework myself. It would have no sense to rely on object inside the UWP framework itself.

SuperJMN
  • 13,110
  • 16
  • 86
  • 185

1 Answers1

1

You could use the TextBlock's Measure method to measure both width and height. It's kind of hacky but does the job.

private Size MeasureString(string textToMeasure, Size availableSize, double fontSize, string fontFamily)
{
    var tb = new TextBlock();

    tb.TextWrapping = TextWrapping.Wrap;
    tb.Text = textToMeasure;
    tb.FontFamily = new FontFamily(fontFamily);
    tb.FontSize = fontSize;
    tb.Measure(new Size(Double.PositiveInfinity, double.PositiveInfinity));

    return new Size(tb.ActualWidth, tb.ActualHeight);
}

The trick here is to use an infinite size in the measure method to get the actual size.

Another viable option would be to user Microsoft's Win2D UWP library. It has a CanvasFontFace class that contains everything you're looking for. I haven't personally used it but it should work for your purposes.

Timo Salomäki
  • 7,099
  • 3
  • 25
  • 40
  • Sorry, but that's not an option for me. I'm creating a GUI framework and I cannot use any native control to calculate it. – SuperJMN Feb 10 '17 at 14:56
  • @SuperJMN Makes sense. Looks like I edited my post just before you commented. I added another option that doesn't use any native controls. – Timo Salomäki Feb 10 '17 at 14:57
  • OK! please, refer to my new question http://stackoverflow.com/questions/42162481/how-to-calculate-the-height-of-a-fontfamily-with-win2d. It seems that class is used internally. I don't know how to use it, either :( I cannot instantiate it directly and the docs don't explain much. – SuperJMN Feb 10 '17 at 15:05
  • 1
    Oh, my bad. I'll give it a look once I'm on my Windows computer. – Timo Salomäki Feb 10 '17 at 15:07
  • Did you take a look? :) thanks! – SuperJMN Feb 11 '17 at 13:04