I'm trying to align a Label
and a NumericUpDown
by their text baselines. I'm doing it in code, rather than the designer. How do I get the position of the text baseline?
// to render text with baseline at coordinates (pt.X, pt.Y) :
Font myFont = Label1.Font;
FontFamily ff = myFont.FontFamily;
float lineSpace = ff.GetLineSpacing(myFont.Style);
float ascent = ff.GetCellAscent(myFont.Style);
float baseline = myFont.GetHeight(ev.Graphics) * ascent / lineSpace;
PointF renderPt = new PointF(pt.X, pt.Y - baseline));
ev.Graphics.DrawString("Render this string", myFont, textBrush, renderPt);
For the Label control, you can get the position of the bottom of the text this way:
Assuming the .TextAlign is set to TopLeft or TopCenter or TopRight, the bottom of the text in the Label control can be found by this method:
dim btmOfText as single
btmOfText = Label1.Font.GetHeight + Label1.Top
The .GetHeight method returns the height, in pixels of the current font used by the Label.
If the .TextAlign is Middle or Bottom, then you need to do a slightly more complex calculation.
This same method will also work with the NumericUpDown control.
来源:https://stackoverflow.com/questions/1006069/how-do-i-get-the-position-of-the-text-baseline-in-a-label-and-a-numericupdown