计算缩放级别以使图像适合面板

Dan*_*lba 3 .net c# system.drawing 2d

如何计算缩放水平(图形比例)以使任何图像适合任何面板?

图像大小和图片大小可以是任何大小。

我需要的方法签名如下:

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

提前致谢。

lin*_*ogl 5

面板和图像的宽高比是答案的关键。

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
     ;
Run Code Online (Sandbox Code Playgroud)

如果需要,请添加零除错误检查。