Maintaining the aspect ratio of a control

Any custom Windows Forms control can ensure it's aspect ratio is maintained when sized by overriding the OnSizeChanged method and forcing a specific width-height ratio.

It is possible to create a base-class from which other controls can be derived that manages this ability by providing a property to turn this feature on or off. This is necessary of course if you want to be able to set the initial aspect ratio in the first place. A control that represents say, a 16:9 video screen might explicitly set the ratio in the OnSizeChanged method.

The following class defines a control that, when unlocked, keeps a record of it's aspect ratio and when locked maintains that ratio whenever it's resized.

C#

using System;

using System.ComponentModel;

using System.Drawing;

using System.Windows.Forms;

 

namespace WFTT

{

  /// <summary>

  /// Creates a control with a selectively lockable aspect ratio.

  /// </summary>

  public class AspectBase : ScrollableControl

  {

    public AspectBase()

    {

    }

 

    float _currentRatio;

    bool _lockRatio=false;

    [

    Description("When true the aspect ratio of the control is locked"),

    Category("Behavior")

    ]

    public bool LockRatio

    {

      get{return _lockRatio;}

      set{_lockRatio=value;}

    }

 

    

    protected override void OnSizeChanged(EventArgs e)

    {

      if(!_lockRatio)

        this._currentRatio=(float)this.Height/(float)this.Width;

      else

        this.Height=(int)(this.Width*this._currentRatio);

 

      base.OnSizeChanged (e);

    }

 

 

  }

}

 

VB

Imports System

Imports System.ComponentModel

Imports System.Drawing

Imports System.Windows.Forms

 

 

Namespace WFTT

   '/ <summary>

   '/ Creates a control with a selectively lockable aspect ratio.

   '/ </summary>

  

   Public Class AspectBase

    Inherits ScrollableControl

    

    Public Sub New()

    End Sub 'New

    

    Private _currentRatio As Single

    Private _lockRatio As Boolean = False

    

    <Description("When true the aspect ratio of the control is locked"), Category("Behavior")>  _

    Public Property LockRatio() As Boolean

     Get

      Return _lockRatio

     End Get

     Set

      _lockRatio = value

     End Set

    End Property

     

    

    Protected Overrides Sub OnSizeChanged(e As EventArgs)

     If Not _lockRatio Then

      Me._currentRatio = CSng(Me.Height) / CSng(Me.Width)

     Else

      Me.Height = CInt(Me.Width * Me._currentRatio)

     End If

     MyBase.OnSizeChanged(e)

    End Sub 'OnSizeChanged

   End Class 'AspectBase

End Namespace 'WFTT

Any custom control deriving from this class will inherit the ability to maintain it's aspect ratio.

Return to the Windows Forms Tips and Tricks page.