2012-02-20 98 views
3

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

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

方法签名我需要的是以下几点:提前

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

感谢。

回答

4

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

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 
    ; 

如果需要,可以添加除数为零的错误检查。

+0

我不是一般的三元布尔运算符的忠实粉丝,但是这非常优雅。做得好。 – Beska 2012-02-20 19:10:15

+0

谢谢,我用你的答案; (btw var应该用小数或浮点数来代替) – kite 2014-09-12 02:59:15

0

通常,容器的宽度或高度(取决于您想要的尺寸)除以您放入的对象的宽度或高度。这会给你调整你需要对图像进行调整。