C#界面动态布局 界面控件随着界面大小尺寸变化而变化

来源:互联网 发布:java常用的技术有哪些 编辑:程序博客网 时间:2024/05/17 21:19

要想写一个漂亮的界面,光靠利用Anchor和Dock属性是远远不够的,我们需要用到相对布局,就是不管窗口大小怎么变化,控件相对父控件的相对位置保持不变。可惜c#里没有提供按照百分比布局。所以只能自己再resize()事件里调整控件位置。

首先在窗体的构造函数里保存父窗体的长宽,以及每个控件的X,Y坐标的相对位置:

 int count = this.Controls.Count * 2 + 2;
            float [] factor=new float [count];
            int i = 0;
            factor[i++] = Size.Width;
            factor[i++] = Size.Height;
            foreach (Control ctrl in this.Controls)
            {
                factor[i++] = ctrl.Location.X / (float)Size.Width;
                factor[i++] = ctrl.Location.Y / (float)Size.Height;
                ctrl.Tag = ctrl.Size;
            }
            Tag = factor;

然后 在sizeChange事件中调整控件大小


            int i = 2;
            foreach (Control ctrl in this.Controls)
            {
                ctrl.Left = (int)(Size.Width * factor[i++]);
                ctrl.Top = (int)(Size.Height * factor[i++]);
                ctrl.Width = (int)(Size.Width / (float)factor[0] * ((Size)ctrl.Tag).Width);
                ctrl.Height = (int)(Size.Height / (float)factor[1] * ((Size)ctrl.Tag).Height);
            }

0 0