Search code examples
c#winformsfontsfontmetrics

Get exact height of WinForms Font in pixels


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.


Solution

  • To get pixels, you use conversion formula:

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

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