views:

32

answers:

2

I have a control on my form , and i want to be able to control the width, and have the height of the control change to maintain its original aspect ratio. So that brings me to the following questions:

Questions:

  • How do you determine the exact aspect ratio of a control?
  • What do i do in the resize event to set the height to the correct aspect for the new width?
+1  A: 

Aspect ratio is width / height. E.g., 640 x 480 dimension screen is 4:3 aspect ratio, or 1.33333.

On form load you can persist the aspect ratio of your controls by dividing width by height and persisting to a variable, and then on form resize reset the height of each control to match what the saved aspect ratio is, by doing

myControl.Height = Math.Round(myControl.Width x mySavedRatio);
RedFilter
+1  A: 

The aspect ratio is simply the ratio of one axis to the other: Width/Height.

To retain the aspect ratio, given a target (newWidth, newHeight), you simply have to make sure that (newWidth/newHeight) == (Width/Height)

To achieve this you have to (e.g.) decide whether the width or the height is the most important axis. If you fix width, then you can calculate the height from the width to retain the aspect ratio:

newWidth = newWidth;
newHeight = newWidth * (Height / Width)

To enforce this, you just need to sit on the Resize event so that you control the size whenever any attempt is made to resize your control:

private void Form1_Resize(object sender, System.EventArgs e)
{
    sender.Size = new Size(control.Size.Width, control.Size.Width * desiredAspectRatio);
}
Jason Williams