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

标签 c# .net 2d system.drawing

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

图片大小和图片大小可以是任意大小。

我需要的方法签名如下:

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

提前致谢。

最佳答案

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

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
     ;

如果需要,添加对被零除错误的检查。

关于c# - 计算缩放级别以使图像适合面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366548/

相关文章:

javascript - 关于文件上传的查询

c# - 将 int32 转换为 16 进制字符串

unity-game-engine - Unity 2D Trail 渲染器碰撞

C#: 2D sub-Tile Line 相交

java - 碰撞检测图形 2D

c# - GroupBy 的 LINQ 错误

c# - 从另一个类文件访问 MainForm

c# - 将 Index() 从 NEST 分派(dispatch)到 Elasticsearch.NET 失败

c# - 使用 BCrypt 将 PHP 转换为 C#

.net - 带有 For Each 循环的 If 语句或Where 扩展?