您的位置:首页 > 编程语言 > C#

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

2015-11-27 14:36 621 查看
按照比例缩放窗体控件及字体,如需等比例缩放,只需将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 > 0)
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[0]) * newx);
int height = (int)(Convert.ToSingle(mytag[1]) * newy);
int x = (int)(Convert.ToSingle(mytag[2]) * newx);
int y = (int)(Convert.ToSingle(mytag[3]) * newy);
con.Location = new Point(x, y);
con.Size = new System.Drawing.Size(width, height);
Single currentSize = Convert.ToSingle(mytag[4]) * newy;
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);

if (con.Controls.Count > 0)
{
SetControls(newx, newy, con);
}
}
}


代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: