应用程序在大屏幕上崩溃

时间:2012-09-24 08:40:51

标签: android

我有这个功能:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

示例:

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

答案 2 :(得分:0)

要将dp转换为px,您可以使用以下内容:

int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dp, context.getResources().getDisplayMetrics());

答案 3 :(得分:0)

它抱怨你试图获得超出位图范围的像素。这可能只是一个四舍五入的问题。也许您计算的width是一个大于实际位图宽度的像素。如果您未在0.5f功能中添加dp2px()会怎样?

相关问题