标签文字显得太低

时间:2014-11-03 10:30:36

标签: c# .net winforms label

我希望以全屏方式显示两个数字,
彼此相对,
尽管不论实际屏幕尺寸如何。

        //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(tops)的舍入误差外,一切都应该有效 我也尝试使字体大小小于标签高度,这有点帮助,但肯定不是一个修复 我实际上虽然文本标志应该涵盖这一点,因为它就是它的用途 同时chaning textalign的height-comp(低中间顶部)并没有改变任何东西,而left / center / right确实有所不同

Screen of misaligned numbers

可能导致此问题的原因是什么?

1 个答案:

答案 0 :(得分:3)

字体的默认度量单位是点,而不是像素。例如,默认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);