Maintain a controls Aspect Ratio on Resize

2019-08-15 11:43发布

问题:

I have a panel control with a picture box in it. How can I maintain the aspect ratio of the panel control when Resizing the form it's on?

回答1:

You'll need to store off the aspect ratio somehow, whether it's something known to you at design time or if you just want to calculate it in the constructor of the form after InitializeComponent(). In your form's Resize event, you'll just need to set the size of the Panel to be the largest rectangle at that aspect ratio that fits within the ClientRectangle of the form.



回答2:

Use the Anchor property, or put the control in a DockContainer and use the Dock property appropriately.

Edit: Actually that's not what you asked, is it? My recommendation would be to do this manually on the resize event of the container. You'd need to calculate the x or y and apply the aspect ratio of the picture when it was loaded.