形状的高度和宽度之间的比率应该是恒定的

时间:2014-04-04 14:39:15

标签: c# height width

我有一个带有两个图片框和一些按钮的表单,我希望它们根据屏幕分辨率自行组织。这是我的代码:

public partial class Form1 : Form
    {         
        int SystemWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
        int SystemHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
        double ratio;

        public Form1()
        {               
            InitializeComponent();
            this.Width = SystemWidth-200;
            this.Height = SystemHeight-200;
           // this.WindowState = FormWindowState.Maximized;

            ratio= SystemWidth / SystemHeight;

        }

        private void Form1_Resize(object sender, EventArgs e)
        {           
            Anordnen();  
        }

        private void Anordnen()
        {
            pic1.Width = this.ClientSize.Width / 2 - 30;
            pic2.Width = this.ClientSize.Width / 2 - 30;
            pic1.Left = 20;
            pic2.Left = pic1.Right + 20;

            btnVergleichen.Left = pic1.Right + 10 - btnVergleichen.Width / 2;
            btnEinlesen1.Left = pic1.Left + pic1.Width / 2 - btnEinlesen1.Width / 2;
            btnBewerten1.Left = pic1.Left + pic1.Width / 2 - btnBewerten1.Width / 2;
            btnEinlesen2.Left = pic2.Left + pic2.Width / 2 - btnEinlesen2.Width / 2;
            btnBewerten2.Left = pic2.Left + pic2.Width / 2 - btnBewerten2.Width / 2;
        }

现在我希望SystemWidth和SystemHeight之间的比率始终保持不变。如果我放大窗体的宽度,高度应该自动变大。我所有的尝试都失败了

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public partial class Form1 : Form
{         
    int SystemWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
    int SystemHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
    private readonly double Ratio;
    private int oldWidth;
    private int oldHeight;

    public Form1()
    {               
        InitializeComponent();

        Ratio = (double)SystemWidth / SystemHeight;
        Size = new Size((int)(SystemWidth - 200 * Ratio), SystemHeight - 200);
    }

    protected override void OnResizeBegin(EventArgs e)
    {
        oldWidth = Width;
        oldHeight = Height;
        base.OnResizeBegin(e);
    }

    protected override void OnResize(EventArgs e)
    {
        int dw = Width - oldWidth;
        int dh = Height - oldHeight;
        if (Math.Abs(dw) < Math.Abs(dh * Ratio))
            Width = (int)(oldWidth + dh * Ratio);
        else
            Height = (int)(oldHeight + dw / Ratio);
        base.OnResize(e);
    }
}

修改
条件if (dw > dh * Ratio)已替换为if (Math.Abs(dw) < Math.Abs(dh * Ratio))