Search code examples
c#.net2dsystem.drawing

Calculate zoom level to fit an image into a panel


How could I calculate the zoom level (graphics scale) to fit any image to any panel?

The image size and the picture size could be any size.

The method signature I need is the following:

  public float CalculateZoomToFit(Image image, Panel targetPanel)
  {
     // I need to calculate the zoom level to make the picture fit into the panel
     return ???
  }

Solution

  • The ratio of width over height for both the panel and the image is the key for the answer.

    var panel_ratio = targetPanel.Width / targetPanel.Height;
    var image_ratio = image.Width / image.Height;
    
    return panel_ratio > image_ratio
         ? targetPanel.Height / image.Height
         : targetPanel.Width / image.Width
         ;
    

    Add checks for divide-by-zero errors, if you want.