将位图大小调整为固定值但不更改宽高比

Dar*_*der 14 scaling android view bitmap

我正在寻找以下问题的解决方案:如何将a的大小更改Bitmap为固定大小(例如512x128).必须保留位图内容的宽高比.

我认为它应该是这样的:

  • 创建一个空的512x128位图

  • 缩小原始位图以适应512x128像素并保持纵横比

  • 将缩放复制到空位图(居中)

实现这一目标的最简单方法是什么?

所有这一切的原因是,GridView当图像的纵横比不同时,会混淆布局.这是一个截图(除最后一个之外的所有图像的纵横比为4:1):

截图

Coe*_*men 31

试试这个,计算比率,然后重新缩放.

private Bitmap scaleBitmap(Bitmap bm) {
    int width = bm.getWidth();
    int height = bm.getHeight();

    Log.v("Pictures", "Width and height are " + width + "--" + height);

    if (width > height) {
        // landscape
        float ratio = (float) width / maxWidth;
        width = maxWidth;
        height = (int)(height / ratio);
    } else if (height > width) {
        // portrait
        float ratio = (float) height / maxHeight;
        height = maxHeight;
        width = (int)(width / ratio);
    } else {
        // square
        height = maxHeight;
        width = maxWidth;
    }

    Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);

    bm = Bitmap.createScaledBitmap(bm, width, height, true);
    return bm;
}
Run Code Online (Sandbox Code Playgroud)

  • 加上一个简单的解决方案.但我会将int ratio更改为float/double ratio,因为int/int在尝试除以0时可能会产生异常. (2认同)

joa*_*gcd 19

Coen Damen的答案并不总是尊重Max Height和Max Width.这是一个答案:

 private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
    if (maxHeight > 0 && maxWidth > 0) {
        int width = image.getWidth();
        int height = image.getHeight();
        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;

        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > 1) {
            finalWidth = (int) ((float)maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float)maxWidth / ratioBitmap);
        }
        image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
        return image;
    } else {
        return image;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 窃取我的答案很好.当然maxWidth和maxHeight是类变量而不是方法参数. (4认同)