[原创]C#按比例缩放窗体控件及字体

时间:2023-12-28 13:38:14

按照比例缩放窗体控件及字体,如需等比例缩放,只需将x,y的比例设置成相同即可。

为了减小误差,建议使用原始尺寸来计算比例。

 private float X, Y;

         private bool b = false;

         public MainForm()
{
InitializeComponent(); X = this.Width;
Y = this.Height; SetTag(this); b = true;
} protected override void OnSizeChanged(EventArgs e)
{
if (!b) return; float newx = (this.Width) / X;
float newy = this.Height / Y;
SetControls(newx, newx, this); base.OnSizeChanged(e);
} /// <summary>
/// 存储原始控件参数
/// </summary>
/// <param name="cons"></param>
private void SetTag(Control cons)
{
foreach (Control con in cons.Controls)
{
con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
if (con.Controls.Count > )
SetTag(con);
}
} /// <summary>
/// 按照比例缩放控件大小及字体
/// </summary>
/// <param name="newx"></param>
/// <param name="newy"></param>
/// <param name="cons"></param>
private void SetControls(float newx, float newy, Control cons)
{
foreach (Control con in cons.Controls)
{
string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
int width = (int)(Convert.ToSingle(mytag[]) * newx);
int height = (int)(Convert.ToSingle(mytag[]) * newy);
int x = (int)(Convert.ToSingle(mytag[]) * newx);
int y = (int)(Convert.ToSingle(mytag[]) * newy);
con.Location = new Point(x, y);
con.Size = new System.Drawing.Size(width, height);
Single currentSize = Convert.ToSingle(mytag[]) * newy;
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > )
{
SetControls(newx, newy, con);
}
}
}

代码