3

I want to get the exact distance between the baseline of the text and the bottom border of a label in C#. I want this because I want to draw a line under the text (don't want to use underlined font, because it's so tight/close to the text).

Here is my try:

//This is placed in the custom label class
int dy = (int)((ClientRectangle.Height - Font.GetHeight())/2);

But it's not exact, the dy returns about 3 and the line drawn to the label is too far from the baseline of the text.

King King
  • 61,710
  • 16
  • 105
  • 130
  • If 3 is too far, you don't have much leeway. Can't you just substract 1 or 2? – 0xFF Apr 18 '13 at 13:34
  • Subtracting a constant from it is called hard code and when the dpi changes, it will be wrong rendered. Thanks. – King King Apr 18 '13 at 13:46
  • If it bothers you to hardcode it then just calculate a % and remove it. But still, that wouldn't make a lot of difference. – 0xFF Apr 18 '13 at 13:52
  • % calculation is not exact and doesn't scale according to the changes of dpi. However, I tested another method and it seems to work, I just replace Font.GetHeight() with Font.SizeInPoints but I'm not sure if it works when the dpi changes. – King King Apr 18 '13 at 14:14
  • I don't see why a % wouldn't be fine. If you want your line to be halfway between the baseline and the border, 50% of `dy` would do the job. You only have to determine which % value place the line where you want it and use that value. – 0xFF Apr 18 '13 at 14:25
  • The % calculation is based on the formula FontHeight * x /100, you think that is also the formula of FontHeight calculated from dpi (and maybe from many other factors that I don't know), don't you? They may increase or decrease together but the changing rates are not the same. I don't know how to express this well and haven't tested it yet, but it's almost as I said. Please see the answer below of Neolisk, thank you. – King King Apr 18 '13 at 15:35

1 Answers1

3

To get text baseline for a label, assuming you are inside the custom label class, in the drawing handler.

Font myFont = this.Font;
FontFamily ff = myFont.FontFamily;

float lineSpace = ff.GetLineSpacing(myFont.Style);
float ascent = ff.GetCellAscent(myFont.Style);
float baseline = myFont.GetHeight(e.Graphics) * ascent / lineSpace;

Credit goes here.

Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • 1
    Hey, this is more exact than the method I tested with Font.SizeInPoints which has the similar result (the line is a little farther from the baseline but the difference is very small and acceptable). Thanks. – King King Apr 18 '13 at 15:41