2010-04-29 55 views
9

如果我有一个我知道高度和宽度的图像,如何将它放在具有最大可能尺寸的矩形中而不会拉伸图像。使图像适合长方形

伪代码已经足够了(但我打算在Java中使用它)。

谢谢。


所以,根据答案,我写了这个:但它不起作用。我做错了什么?

double imageRatio = bi.getHeight()/bi.getWidth(); 
double rectRatio = getHeight()/getWidth(); 
if (imageRatio < rectRatio) 
{ 
    // based on the widths 
    double scale = getWidth()/bi.getWidth(); 
    g.drawImage(bi, 0, 0, (int) (bi.getWidth() * scale), (int) (bi.getHeight() * scale), this); 
} 
if (rectRatio < imageRatio) 
{ 
    // based on the height 
    double scale = getHeight()/bi.getHeight(); 
    g.drawImage(bi, 0, 0 , (int) (bi.getWidth() * scale), (int) (bi.getHeight() * scale), this); 
} 
+0

你的意思是保持拟合方面宽高比? – 2010-04-29 19:11:30

+0

@SB:我认为是这样(我不明白你的意思是什么......)所以,源图像和缩放图像的宽度和高度的比例必须相同。 – 2010-04-29 19:13:20

回答

15

确定两者的纵横比(高度除以宽度,比方说,这么高,瘦矩形的纵横比> 1)。

如果矩形的长宽比大于图像的宽高比,则根据宽度(矩形宽度/图像宽度)均匀缩放图像。

如果矩形的纵横比小于图像的纵横比,则根据高度(矩形高度/图像高度)均匀缩放图像。

+0

你能看看我的更新吗? – 2010-04-29 19:41:15

+0

据我所知,它看起来像你正在做我的建议,我想我再次检查我的逻辑。这些值是否正确,你在每一步都抓住了? (是bi.GetWidth()和GetHeight()都给你正确的数字?)(我不是一个Java程序员,但我昨晚留在了快捷假日酒店!)) – John 2010-04-29 19:49:51

+0

我发现它:不使用双打 – 2010-04-29 20:15:43

7

这里是我的两分钱:

/** 
* Calculate the bounds of an image to fit inside a view after scaling and keeping the aspect ratio. 
* @param vw container view width 
* @param vh container view height 
* @param iw image width 
* @param ih image height 
* @param neverScaleUp if <code>true</code> then it will scale images down but never up when fiting 
* @param out Rect that is provided to receive the result. If <code>null</code> then a new rect will be created 
* @return Same rect object that was provided to the method or a new one if <code>out</code> was <code>null</code> 
*/ 
private static Rect calcCenter (int vw, int vh, int iw, int ih, boolean neverScaleUp, Rect out) { 

    double scale = Math.min((double)vw/(double)iw, (double)vh/(double)ih); 

    int h = (int)(!neverScaleUp || scale<1.0 ? scale * ih : ih); 
    int w = (int)(!neverScaleUp || scale<1.0 ? scale * iw : iw); 
    int x = ((vw - w)>>1); 
    int y = ((vh - h)>>1); 

    if (out == null) 
     out = new Rect(x, y, x + w, y + h); 
    else 
     out.set(x, y, x + w, y + h); 

    return out; 
} 
+0

感谢这个Mobistry。 – Robinson 2013-02-17 18:36:38