C#按比例缩放窗体控件及字体

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

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

1 private float X, Y;
 2 
 3         private bool b = false;
 4 
 5         public MainForm()
 6         {
 7             InitializeComponent();
 8 
 9             X = this.Width;
10             Y = this.Height;
11 
12             SetTag(this);
13 
14             b = true;
15         }
16 
17         protected override void OnSizeChanged(EventArgs e)
18         {
19             if (!b) return;
20             
21             float newx = (this.Width) / X; 
22             float newy = this.Height / Y;
23             SetControls(newx, newx, this);
24 
25             base.OnSizeChanged(e);
26         }
27 
28         /// <summary>
29         /// 存储原始控件参数
30         /// </summary>
31         /// <param name="cons"></param>
32         private void SetTag(Control cons)
33         {
34             foreach (Control con in cons.Controls)
35             {
36                 con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
37                 if (con.Controls.Count > 0)
38                     SetTag(con);
39             }
40         }
41 
42         /// <summary>
43         /// 按照比例缩放控件大小及字体
44         /// </summary>
45         /// <param name="newx"></param>
46         /// <param name="newy"></param>
47         /// <param name="cons"></param>
48         private void SetControls(float newx, float newy, Control cons)
49         {
50             foreach (Control con in cons.Controls)
51             {
52                 string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
53                 int width = (int)(Convert.ToSingle(mytag[0]) * newx);
54                 int height = (int)(Convert.ToSingle(mytag[1]) * newy);
55                 int x = (int)(Convert.ToSingle(mytag[2]) * newx);
56                 int y = (int)(Convert.ToSingle(mytag[3]) * newy);
57                 con.Location = new Point(x, y);
58                 con.Size = new System.Drawing.Size(width, height);
59                 Single currentSize = Convert.ToSingle(mytag[4]) * newy;
60                 con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
61 
62                 if (con.Controls.Count > 0)
63                 {
64                     SetControls(newx, newy, con);
65                 }
66             }
67         }

代码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值