2012-02-14 31 views
0

我有一个函数用于确定图像在特定矩形内的绝对最大尺寸(同时保留其纵横比)。我目前使用的代码肯定是错误的,但我不确定我出错的地方。确定图像可以在矩形内的最大可能尺寸

// Sets the image to the largest proportional size possible 
// based on the current browser window dimensions and original 
// image size specified by the image loader 
function applyLargestProportionalSize() { 
    var maxWidth = <width of container>; 
    var maxHeight = <height of container>; 

    var realWidth = <actual image width>; 
    var realHeight = <actual image height>; 

    if (realWidth < realHeight && maxWidth > maxHeight) { 
     var scaledWidth = Math.min(realWidth, maxWidth); 
     $('img').css('width', scaledWidth); 
     // let height be determined by the browser 
    } else { 
     var scaledHeight = Math.min(realHeight, maxHeight); 
     $('img').css('height', scaledHeight); 
     // let width be determined by the browser 
    } 
} 
+1

您如何知道代码错误?它出什么问题了? – 2012-02-14 23:55:35

回答

1

我不知道的JavaScript,但问题是,你的代码只能处理的案件中,容器的纵横比小于1,并且图像的长宽比大于一(或者我可能倒退了,我不确定长宽比的确切定义)。试试这个:

if (realWidth/realHeight > maxWidth/maxHeight) { 
    // everything else the same 
+0

这工作,谢谢! – 2012-02-15 00:14:39

0

缩放图像尺寸为两种情况:

  1. 要匹配容器的高度,在这种情况下,你会得到一个宽度

    scaled_width = image_width * container_height/image_height 
    scaled_height = container_height 
    
  2. 要匹配容器的宽度,在这种情况下你得到一个高度

    scaled_height = image_height * container_width/image_width 
    scaled_width = container_width 
    

然后选择计算出的尺寸适合容器内的第一个尺寸。

如果图像和容器具有相同的纵横比,则它们都适合。

如果图像比容器更窄,只有第一个适合。

如果图像比容器更宽,只有第二个适合。

+0

至少在这部分中,“如果图像和容器具有相同的纵横比,则它们都适合。”,使用此方法进行浮点比较时是否会遇到一些问题? – 2012-02-15 00:15:48

+0

碰巧,算法在整数运算中运行正常---我故意先把乘法放在第一位。但即使你是以浮动的方式来做,也不重要,因为我们不关心它们是否与epsilon不同。它们两者都适合的事实更多地是对算法做什么的评论,而不是正确操作的必要性。 – zgpmax 2012-02-15 00:24:39