我有这个功能:
public static Bitmap getResizedBitmap(Bitmap bm,Context c) {
int width =(int) dp2px(bm.getWidth(),c);
int height = (int) dp2px(bm.getHeight(),c);
float scaleWidth = ((float) 250) / width;
float scaleHeight = ((float) 170) / 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;
}
其中 dp2px 是:
private static float dp2px(int dip, Context context){
float scale = context.getResources().getDisplayMetrics().density;
return dip * scale + 0.5f;
}
在大多数屏幕上都可以,但例如在 Galaxy s3 上它会返回
java.lang.IllegalArgumentException: x+width 必须 <= bitmap.width()
在这条线上:
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);