0
votes

This is possibly a duplicate question, but I am unable to find the answer.

My only question is how to get height (ascent + descent, without any spacing) of the Font used in WinForms in pixels. I have Segoe UI 8.25 Regular font.

Font.Height gives me 15 (pixels?)

I am able to get font metrics ans use FontFamily:

  • GetEmHeight gives me 2048.
  • GetCellAscent gives me 2210 (larger than EM?)
  • GetCellDescent gives me 514

According to formula from MSDN

I should do following:

(ascent + descent) * font.Height / emHeight
which is
(514 + 2210) * 15 / 2210 = 19 pixels.

So:

  • Calculating using MSDN's formulas gives me 19px text height.
  • TextRenderer.MeasureText for "Tg" string gives me 13px.
  • If a take a screenshot and measure it in Photoshop (from lowest bound of g to highest bound of T) i'll receive 10px.

What I'm doing wrong and how this values are interconnected? The goal is to get something as closer as possible to screenshot's measuring results.

TextRenderer.MeasureText uses much of resources and I can't use it anytime during draw.

1
What are you trying to achieve ?aybe
To get pixels, you use conversion formula.Héctor Manuel Martínez Durán
@Aybe just want to know the height of text for render calculations. If the text is definitely single-lined, there is no need to calculate the wordwrap (which is resource extensive) and the font's height is enough.rattler
You are using Font.Height where your reference is using Font.Size.TnTinMn
It is the same as the answer from @HéctorManuelMartinezDurán, to whom you owe an apology for your comment to his answer.TnTinMn

1 Answers

5
votes

To get pixels, you use conversion formula:

descentPixel = font.Size * descent / fontFamily.GetEmHeight(FontStyle.Regular);

From this link https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-obtain-font-metrics