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?
How do I get the position of the text baseline in a Label and a NumericUpDown?
// 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.
GetHeight does not return the position of the baseline of the font, but the position of the top of the next line. Windoze fonts are screwed in this way. There is no simple answer here. –
Balladist
I noticed that Stewbob was unhappy with my downvoting of his answer, and has retaliated by downvoting a number of my posts. I am taking the high road here and not escalating this into an all-out war. –
Balladist
@dar7yl...Umm...who are you? I see you have comments to my post, but I don't understand the last one? –
Rennie
@dar7yl: I've done some investigating. It turns out that one of my employees in a misguided and idiotic expression of loyalty acted like a jerk. We've had a talk about professionalism and needless to say, this won't happen again, and the entire department is getting their own personal copy of "The Clean Coder". My apologies on behalf of our organization. Let me know how much reputation that you lost, and I will see that it is restored. ...No coders were harmed during the course of this investigation (but it came close). –
Rennie
@dar7yl: The inappropriate votes have been changed. Thanks for bringing this to my attention. –
Rennie
Thank you for your considerate and professional response. My faith in humanity has been restored. –
Balladist
© 2022 - 2024 — McMap. All rights reserved.