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;
}
}
,我知道有一種方法來檢查,如果控制是一個標籤,但這並不似乎是它。
嘗試使用,而不是'is'運算符'==比較類型時'。 – Roy123
foreach(Label i in Controls)無法工作,因爲您嘗試將非標籤控件放入標籤中。 – GuidoG
字體是一種環境屬性,如果您設置了父級控件的字體,則其所有子級都將使用相同的字體。所以我不認爲你需要一個循環來爲所有控件分配字體,除非你需要將字體應用到特定類型的所有子控件,在這種情況下,你可以看看[這篇文章](http:///stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button)。 –