0

我有这个功能:

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);
4

4 回答 4

1

在 manifest.xml 中使用它

 <supports-screens 
android:resizeable="true" 
android:smallScreens="true" 
android:normalScreens="true" 
android:largeScreens="true" 
android:anyDensity="true"/>

http://developer.android.com/guide/practices/screens_support.html

于 2012-09-24T08:56:43.390 回答
0

除了你的代码。您是否已将支持屏幕标签相应地添加到您的清单中?

例子:

<supports-screens android:normalScreens="true" android:resizeable="true"     android:anyDensity="true" android:largeScreens="true" android:smallScreens="true" android:xlargeScreens="true"></supports-screens>
于 2012-09-24T08:48:41.840 回答
0

要将 dp 转换为 px,可以使用以下命令:

int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dp, context.getResources().getDisplayMetrics());
于 2012-09-24T08:56:25.283 回答
0

它抱怨您试图在位图范围之外获取像素。这可能只是一个四舍五入的问题。也许您计算width的像素比实际位图宽度大一个像素。如果您不在函数中添加 会发生0.5f什么dp2px()

于 2012-09-24T08:56:35.363 回答