使图像适合矩形

时间:2010-04-29 19:08:34

标签: java image max

如果我有一张我知道高度和宽度的图像,我怎样才能将它放在一个尺寸最大的矩形中,而不会拉伸图像。

伪代码就足够了(但我将在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);
}

3 个答案:

答案 0 :(得分:15)

确定两者的纵横比(高度除以宽度,例如,如此高,瘦的矩形的纵横比> 1)。

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

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

答案 1 :(得分:8)

这是我的两分钱:

/**
 * 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;
}

答案 2 :(得分:0)

这不会影响您的宽高比,并且完全适合一侧,而另一侧不会过冲。

public static Rect getScaled(int imgWidth, int imgHeight, int boundaryWidth, int boundaryHeight) {

    int original_width = imgWidth;
    int original_height = imgHeight;
    int bound_width = boundaryWidth;
    int bound_height = boundaryHeight;
    int new_width = original_width;
    int new_height = original_height;

    // first check if we need to scale width
    if (original_width > bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    // then check if we need to scale even with the new height
    if (new_height > bound_height) {
        //scale height to fit instead
        new_height = bound_height;
        //scale width to maintain aspect ratio
        new_width = (new_height * original_width) / original_height;
    }

    return new Rect(0,0,new_width, new_height);
}