11

I would like to know how to calculate the height of a given a font (with its properties, like size, weight, style...) in a Window Universal Application using Win2D.

I previously used a CanvasTextLayout, but it requires a text to work, like in this line:

var ctl = new CanvasTextLayout(session, "Some text", new CanvasTextFormat(), constraintWidth, constraintHeight);

In my case, I will NOT have a text because what I'm looking for is the height in which all the glyphs of a given font (with its style, size, weight...) are fit.

EDIT: I have also tried with the CanvasFontFace class, but it seems it doesn't have any public constructor.

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • Are you looking for GetGlyphRunBounds https://microsoft.github.io/Win2D/html/Overload_Microsoft_Graphics_Canvas_Text_CanvasFontFace_GetGlyphRunBounds.htm ? otherwise CanvasTexFormat has a FontSize property, as usual with font families – Simon Mourier Feb 15 '17 at 19:21
  • I think GetGlyphRunBounds is not what I need, since I would have to specify at least one glyph. It's the exact equivalent to this question, but in Win2D. http://stackoverflow.com/questions/4509613/how-to-calculate-font-height-in-wpf. Please, see the answer. In WPF it's call "LineSpacing". – SuperJMN Feb 15 '17 at 19:58
  • I don't think you can get the default `LineSpacing` like in WPF. You will have to draw the text first. This is a limitation of Win2D. – Justin XL Feb 16 '17 at 02:37
  • Ok, now the question is clear :). CanvasTextFormat has a LineSpacing property: https://microsoft.github.io/Win2D/html/P_Microsoft_Graphics_Canvas_Text_CanvasTextFormat_LineSpacing.htm – Simon Mourier Feb 16 '17 at 06:41
  • It has the property, but it's always -1. I think it's not what we are looking for :( – SuperJMN Feb 16 '17 at 07:51

1 Answers1

5

But you are already on the right way. Use e. g. fg as text. The f allocates the upper area, the g the lower one, so you get the total height of a text in the current font of the canvas.

Chris Tophski
  • 930
  • 1
  • 6
  • 23
  • That's a hack after all ;) – SuperJMN Feb 17 '17 at 14:48
  • Maybe, but I have seen and used this quite often without any problems. In fact, I haven't found a satisfactory alternative, yet. I'd be very curious, though. I remember I've been having problems with either too small or too big values or poor performance, trying to solve this in another way. – Chris Tophski Feb 17 '17 at 14:57
  • Oh, and `LineSpacing` in the sense of typography might include additional height units in order to set a multi-line text aestetically well. I'm not sure if there are cases, where `LineSpacing` in Wpf or similar behaves that way. If you really just want the actual text height without any possible additional space, this solution should be correct by definition, because it concentrates on the metrics of the glyphs the current font would produce. – Chris Tophski Feb 17 '17 at 23:15