gpt4 book ai didi

c# - 调整 Window Forms 应用程序大小时如何保持纵横比?

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:04 24 4
gpt4 key购买 nike

我需要一些有关窗口窗体调整大小的帮助,这个 Form1 默认打开,大小为 800x600,但它以编程方式更改其大小,使用下面的代码我试图使用新的保持窗口窗体的外观大小值,但我的问题是,在调整窗口窗体大小时,它失去了它的预期方面,我不知道如何修复它。

举个简单的例子,当前窗口大小是宽度 800,高度 600,如果调整大小它应该保持纵横比。假设窗口窗体的宽度调整为 850,我希望高度为 650。对吗?

    public Form1()
{
InitializeComponent();

// Default Window Size
ClientSize = new Size(800, 600);
chromeWidth = Width - ClientSize.Width;
chromeHeight = Height - ClientSize.Height;


}

// Window form Size changes programatically from a size handler, updating "ClientSize".


//////////////////////////// Resize /////////////////////////////////////

#region Resizer
private float constantWidth = 1;//16;
private float constantHeight = 1;//9;

private int chromeWidth;
private int chromeHeight;

// From Windows SDK
private const int WM_SIZING = 0x214;

private const int WMSZ_LEFT = 1;
private const int WMSZ_RIGHT = 2;
private const int WMSZ_TOP = 3;
private const int WMSZ_BOTTOM = 6;

struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}



protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_SIZING)
{
RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));

int w = rc.Right - rc.Left - chromeWidth;
int h = rc.Bottom - rc.Top - chromeHeight;

switch (m.WParam.ToInt32()) // Resize handle
{
case WMSZ_LEFT:
case WMSZ_RIGHT:
// Left or right handles, adjust height
rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
break;

case WMSZ_TOP:
case WMSZ_BOTTOM:
// Top or bottom handles, adjust width
rc.Right = rc.Left + chromeWidth + (int)(constantWidth * h / constantHeight);
break;

case WMSZ_LEFT + WMSZ_TOP:
case WMSZ_LEFT + WMSZ_BOTTOM:
// Top-left or bottom-left handles, adjust width
rc.Left = rc.Right - chromeWidth - (int)(constantWidth * h / constantHeight);
break;

case WMSZ_RIGHT + WMSZ_TOP:
// Top-right handle, adjust height
rc.Top = rc.Bottom - chromeHeight - (int)(constantHeight * w / constantWidth);
break;

case WMSZ_RIGHT + WMSZ_BOTTOM:
// Bottom-right handle, adjust height
rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
break;
}

Marshal.StructureToPtr(rc, m.LParam, true);
}

base.WndProc(ref m);
}
#endregion

最佳答案

纵横比是一个比例,意思是height/width的结果应该是要保持的纵横比的相同值。除非高度和宽度是相同的值(即正方形),否则简单地改变相同的量不会保持纵横比。

因此,您需要更改高度(或宽度),方法是首先获取纵横比(即 height/width),然后将该值乘以高度以获得宽度(或反之亦然)。

const double Ratio = height / width;

...

height = height + 50; // This works the same if you change the 'width'
width = height * Ratio;

关于c# - 调整 Window Forms 应用程序大小时如何保持纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com