[原創]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         }
代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM