2016-10-11 46 views
1

我有一堆标签,富文本框,文本框和按钮。我一直在搞锚定和自动缩放(dpi /字体),试图让我的UI在多种屏幕分辨率上看起来差不多。到目前为止,我已经取得了一些进展,让控件正确调整大小,但现在我需要在控件更改后调整字体大小。有没有办法调整窗体上的每个控件的字体大小与循环?

我试过this question的解决方案(稍有改动就忽略父容器,只是使用标签本身),这对标签非常适用,但文本框没有绘制事件,所以我无法得到通常会在PaintEventArgs的的e.Graphics传递的信息的缩放比例给予大小的字符串:

public static float NewFontSize(Graphics graphics, Size size, Font font, string str) 
    { 
     SizeF stringSize = graphics.MeasureString(str, font); 
     float wRatio = size.Width/stringSize.Width; 
     float hRatio = size.Height/stringSize.Height; 
     float ratio = Math.Min(hRatio, wRatio); 
     return font.Size * ratio; 
    } 

    private void lblTempDisp_Paint(object sender, PaintEventArgs e) 
    { 
     float fontSize = NewFontSize(e.Graphics, lblTempDisp.Bounds.Size, lblTempDisp.Font, lblTempDisp.Text); 
     Font f = new Font("Arial", fontSize, FontStyle.Bold); 
     lblTempDisp.Font = f; 

    } 

的首要问题:有没有类似的方式调整字体大小文本框?

二级问题:什么是正确的方式来循环我的窗体上的一种类型的所有控件?我想:

foreach (Label i in Controls) 
     { 
      if (i.GetType() == Label)//I get an error here that says 
      //"Label is a type, which is not valid in the given context" 
      { 
       i.Font = f; 
      } 
     } 

,我知道有一种方法来检查,如果控制是一个标签,但这并不似乎是它。

+0

尝试使用,而不是'is'运算符'==比较类型时'。 – Roy123

+0

foreach(Label i in Controls)无法工作,因为您尝试将非标签控件放入标签中。 – GuidoG

+0

字体是一种环境属性,如果您设置了父级控件的字体,则其所有子级都将使用相同的字体。所以我不认为你需要一个循环来为所有控件分配字体,除非你需要将字体应用到特定类型的所有子控件,在这种情况下,你可以看看[这篇文章](http:///stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button)。 –

回答

3

你的第二个问题:

另一种方式是这样的:

foreach (Label label in Controls.OfType<Label>()) 
{ 
    label.Font = f; 
} 
相关问题