简体   繁体   中英

Resize control to match aspect ratio

Description

I am creating a "simulator" for different resolutions. Basically I have a control inside a panel. Then the user can choose an aspect ratio (more information below) and the control inside the simulator should get resized to match the desired ratio.

Problem

The problem is that I do not know what is a good way to calculate the size of the control without having to use a lot of CPU or trying or resizing. How can I know, if I have to resize the height or the width of the control to fit inside the simulator?

The simulator can grow or shrink. That is why I can not be sure, if the control inside of it will fill up the whole width of the simulator, or the height, but the aspect ratio should be always correct.

Hint

This is probably a very easy mathematical problem. I just don't find a solution right now (today is not my day)!

If you have any ideas or suggestions, feel free to ask and propose!

Example

模拟器示例。

Available Resolutions

  • 3:2 (Like on the iPhone until iPhone 5; Anyone knows an other name?)
  • 16:10 (WXGA)
  • 16:9 (Widescreen)
  • 4:3 (VGA)

Thanks for helping!

Here is a little testbed. Put a control on a form and assign the ViewPort variable to it. Here I chose a textBox1 but any control will do. Then pick a target aspect ratio, I chose TargetRatio_3_2. Try it by resizing the form!

Note 1: I chose a form as the Container (your Simulator ) for easier testing and therefore use its ClientRectangle to access its inner measures. Any other Control will basically work the same.

Not 2: I have added a few lines to place the ViewPort (your Control ) in the center.

private void Form1_Resize(object sender, EventArgs e)
{
    Control Container = this;
    Control ViewPort = textBox1;

    float ContainerRatio = 1f * Container.ClientRectangle.Width / Container.ClientRectangle.Height;

    const float TargetRatio_3_2 = 3f / 2f;
    const float TargetRatio_16_9 = 16f / 9f;
    const float TargetRatio_4_3 = 4f / 3f;
    const float TargetRatio_16_10 = 16f / 10f;
    //..

    float TargetRatio = TargetRatio_3_2;

    if (ContainerRatio < TargetRatio)
    {
        ViewPort.Width = Container.ClientRectangle.Width;
        ViewPort.Height = (int)(ViewPort.Width / TargetRatio);
        ViewPort.Top = (Container.ClientRectangle.Height - ViewPort.Height) / 2;
        ViewPort.Left = 0;
    }
    else
    {
        ViewPort.Height = Container.ClientRectangle.Height;
        ViewPort.Width = (int)(ViewPort.Height * TargetRatio);
        ViewPort.Top = 0;
        ViewPort.Left = (Container.ClientRectangle.Width - ViewPort.Width) / 2;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM