使图像适合矩形

Mar*_*aux 9 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);
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 15

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

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

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


Sil*_*ria 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;
}
Run Code Online (Sandbox Code Playgroud)