Android Widget Canvas - java.lang.IllegalArgumentException

时间:2013-08-06 16:27:17

标签: android bitmap widget android-canvas draw

我的应用程序中有一个Widget,它有一个用于显示画布的ImageView。

如果我查看我的用户崩溃,我会经常看到该错误(但总是只在几台设备上):

 java.lang.RuntimeException: Unable to start receiver my.package.name.WidgetProvider: java.lang.IllegalArgumentException: RemoteViews for widget update exceeds maximum bitmap memory usage (used: 5715000, max: 5529600 /*these arent always the same :)*/ ) The total memory cannot exceed that required to fill the device's screen once.

我的画布具有动态大小,当用户调整大小时会自动调整大小,并且具有指定的宽高比,它的创建方式如下:

Resources r = context.getResources();
    SharedPreferences widgets = context.getSharedPreferences("widgets", 0);

            //these are stored in onAppWidgetOptionsChanged when user resizes his widget
    int w = widgets.getInt(widgetId + "_width", 130);
    int h = widgets.getInt(widgetId + "_height", 160);

    w = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, w,
            r.getDisplayMetrics());
    h = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, h,
            r.getDisplayMetrics());

    float scaleX = (float) w / (float) 13;
    float scaleY = (float) h / (float) 16;

    float scale = 1.5f * (scaleX < scaleY ? scaleX : scaleY);//i multiplied it with 1.5 because the canvas was very unsharp

    w = (int) (13 * scale);
    h = (int) (16 * scale);

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
            R.layout.widget);


    Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(bmp);


 [...]

    remoteViews.setImageViewBitmap(R.id.widget, bmp);

    appWidgetManager.updateAppWidget(widgetId, remoteViews);

我想这是因为画布比小部件大1.5倍,但是它非常不锋利。

我该怎么办?

提前致谢。

Metin Kale

1 个答案:

答案 0 :(得分:1)

documentation指定:

  

RemoteViews对象使用的总位图内存不能超过   需要填充屏幕1.5次,即。 (屏幕宽度x屏幕   身高x 4 x 1.5)字节。

因此,使用它来控制位图大小,然后在布局中使用ImageView scaleType fitCenter来缩放以适合窗口小部件中的位图。