Android将多个不同大小的位图绘制到相同大小的画布上

时间:2014-09-08 09:56:38

标签: java android bitmap android-drawable

我在这里有一些不同大小的位图: 我想将它们的大小调整为每个图像的宽度和高度(64px) 这就是我所做的:

int size = Math.round(64 * getResources().getDisplayMetrics().density);
int imagesLength = 4;
Bitmap bmp = Bitmap.createBitmap(size*imagesLength, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
for (int i = 0; i < imagesLength; i++) {
    Bitmap mImage = getImage(i);
    // ...code to get bitmap...
    canvas.drawBitmap(mImage,i * size, 0, null);
}

有人有个主意吗?感谢

1 个答案:

答案 0 :(得分:1)

您可以使用Bitmap.createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)将图像更改为您想要的尺寸。

但这不会保持宽高比不变。如果这很重要,你可能想要别的想法。就像你已经做的那样缩小它,并以某种背景为中心添加它。

无论如何都可以获得方形位图:

int size = Math.round(64 * getResources().getDisplayMetrics().density);
int imagesLength = 4;
Bitmap bmp = Bitmap.createBitmap(size*imagesLength, size, Bitmap.Config.ARGB_8888); // the bitmap you paint to
Canvas canvas = new Canvas(bmp);
for (int i = 0; i < imagesLength; i++) {
    Bitmap mImage = getImage(i);

    // ...code to get bitmap...
    mImage = Bitmap.createScaledBitmap(mImage , size, size, true);

    canvas.drawBitmap(mImage,i * size, 0, null);
}

这是为了保持比例但留下差距:

int size = Math.round(64 * getResources().getDisplayMetrics().density);
int imagesLength = 4;
Bitmap bmp = Bitmap.createBitmap(size*imagesLength, size, Bitmap.Config.ARGB_8888); // the bitmap you paint to
Canvas canvas = new Canvas(bmp);
for (int i = 0; i < imagesLength; i++) {
    Bitmap mImage = getImage(i);

    // ...code to get bitmap...
    int width = mImage.getWidth();
    int height= mImage.getHeight();
    float ratio = width/(float)height;
    if(ratio>1)
    {
        mImage = Bitmap.createScaledBitmap(mImage , size, size/ratio, true);
    }
    else
    {
        mImage = Bitmap.createScaledBitmap(mImage , size*ratio, size, true);
    }

    canvas.drawBitmap(mImage,i * size, 0, null);
}