How do I get the position of the text baseline in a Label and a NumericUpDown?

筅森魡賤 提交于 2020-01-09 11:36:07

问题


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?


回答1:


// 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);



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!