如何有效地调整位图的大小,并在android中失去质量

use*_*941 14 android resize canvas bitmap surfaceview

我有一个Bitmap大小,320x480我需要在不同的设备屏幕上拉伸它,我尝试使用这个:

Rect dstRect = new Rect();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(frameBuffer, null, dstRect, null);
Run Code Online (Sandbox Code Playgroud)

它工作,图像像我想要的那样填满整个屏幕,但图像像素化,看起来很糟糕.然后我尝试了:

float scaleWidth = (float) newWidth / width;
float scaleHeight = (float) newHeight / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(frameBuffer, 0, 0,
                width, height, matrix, true);
canvas.drawBitmap(resizedBitmap, 0, 0, null);
Run Code Online (Sandbox Code Playgroud)

这次它看起来很完美,漂亮和流畅,但是这段代码必须在我的主游戏循环中,并且Bitmap每次迭代创建它都会使它非常慢.如何调整图像大小以使其不会像素化并快速完成?

找到解决方案:

Paint paint = new Paint();
paint.setFilterBitmap();
canvas.drawBitmap(bitmap, matrix, paint);
Run Code Online (Sandbox Code Playgroud)

小智 34

调整位图大小:

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}
Run Code Online (Sandbox Code Playgroud)

非常自我解释:只需输入原始的Bitmap对象和Bitmap的所需尺寸,此方法将返回新调整大小的Bitmap!可能是,它对你有用.

  • 为什么不使用Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap,newWidth,newHeight,false); (7认同)
  • 为了更好的质量缩放图像位图resizedBitmap = Bitmap.createBitmap(bm,0,0,width,height,matrix,true); (4认同)