【问题标题】:Label text appearing too low标签文本显示太低
【发布时间】:2014-11-03 18:47:16
【问题描述】:

我想全屏显示两个数字,
彼此之上,
尽可能不考虑实际屏幕尺寸。

        //getting screen size and setting window to maximized
        Rectangle screenEdge = Screen.PrimaryScreen.Bounds;
        this.Width = screenEdge.Width;
        this.Height = screenEdge.Height;
        this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
        this.WindowState = FormWindowState.Maximized;

        //using 90% of width and 40% (times two) of height
        int lWidth = (int)(this.Width * 0.9);
        int lHeight = (int)(this.Height * 0.4);

        //horiz. spacing: remainder, divided up for left and right
        int lLeft = ( this.Width - lWidth ) / 2;
        //vert. spacing: remainder divided for top, bottom and between
        int lTop = ( this.Height - (2 * lHeight)) / 3 ;

        //the labels holding the numbers
        lSoll = new Label();
        lIst = new Label();

        //setting label lSoll to calc'd dimensions, adding & aligning text
        lSoll.Left = lLeft;
        lSoll.Width = lWidth;
        lSoll.Top = lTop;
        lSoll.Height = lHeight;
        Font sollFont = new Font(FontFamily.GenericSansSerif, lSoll.Height);
        Font sFSized = new Font(sollFont.FontFamily, lSoll.Height);
        lSoll.Font = sFSized;
        lSoll.TextAlign = ContentAlignment.MiddleCenter;
        lSoll.ForeColor = Color.Blue;
        lSoll.BackColor = Color.White;
        updateSollText(42);

        //same as above, just a bit lower
        lIst.Left = lLeft;
        lIst.Width = lWidth;
        lIst.Top = lTop * 2 + lSoll.Height;
        lIst.Height = lHeight;
        Font istFont = new Font(FontFamily.GenericSansSerif, lIst.Height);
        Font iFSized = new Font(istFont.FontFamily, lIst.Height);
        lIst.Font = iFSized;
        lIst.TextAlign = ContentAlignment.TopCenter;
        lIst.ForeColor = Color.Red;
        lIst.BackColor = Color.White;
        updateIstText(39);

此代码的问题(除了笨拙之外):
标签上的文本部分显示在标签的下限下方,即不可见, 请参阅底部的屏幕截图。
我仔细检查了我的计算,发现除了 1 pt(顶部)的舍入误差之外,它都应该有效。
我还尝试让字体大小小于标签高度,这有一点帮助,但肯定不是解决办法。
我实际上虽然 textalign 应该涵盖这一点,因为这就是它的用途。
同样改变 textalign 的 height-comp(low middle top) 并没有改变任何东西,而 left / center / right 确实会产生预期的差异

可能是什么原因造成的?

【问题讨论】:

  • 标签的边缘和字体之间总是有一点填充,这样字母就不会与其他控件重叠。在您的代码中,您将字体大小设置为标签的高度,这意味着它永远不会适合。为什么不转动它并计算字体的高度并将标签上的 autoEllipsis 属性设置为 true(使其自动缩放到文本)。请注意,如果您希望标签覆盖表单的整个宽度,您仍然需要手动设置标签的宽度。

标签: c# .net winforms label


【解决方案1】:

字体的默认度量单位是点,而不是像素。例如,默认 DPI 设置为 96,9 磅字体占用 9 * 96 / 72 = 12 像素。所以你要求的字体太大,不合适。

解决方法很简单,您可以使用带有 GraphicsUnit 参数的 Font 构造函数重载来指定您喜欢的度量单位。修复:

 Font sollFont = new Font(FontFamily.GenericSansSerif, lSoll.Height, GraphicsUnit.Pixel);
 Font sFSized = new Font(sollFont.FontFamily, lSoll.Height, GraphicsUnit.Pixel);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多