Android 小部件 Canvas - java.lang.IllegalArgumentException

标签 android bitmap widget android-canvas draw

我的应用程序中有一个 Widget,它有一个用于显示 Canvas 的 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.

我的 Canvas 有一个动态大小,当用户调整大小时它会自动调整大小,并且有指定的宽高比,它是这样创建的:

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

我猜这是因为 Canvas 比小部件大 1.5 倍,但除此之外它非常不清晰。

我能做什么?

提前致谢。

羽衣甘蓝

最佳答案

documentation指定:

The total Bitmap memory used by the RemoteViews object cannot exceed that required to fill the screen 1.5 times, ie. (screen width x screen height x 4 x 1.5) bytes.

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

关于Android 小部件 Canvas - java.lang.IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085576/

相关文章:

java - 从文件路径将位图设置为 imageview 不起作用

c++ - GDI+ - 将位图像素转换为 JPG 格式

python - 有没有办法清除 Tkinter 中文本小部件的撤消/重做堆栈?

C#:如何将 RAW 图像(格式:rgb565)加载到位图中?

javascript - Django-dashing 创建你自己的小部件

python - wxPython 中的音量指示器

java - Android Java 正则表达式替换重复模式如图所示

android - 在 Playstore 的新管理发布页面中更新推出旁边的百分比表示什么

java - 如何暂停和恢复安卓游戏?

java - 如何从另一个类获取字符串? - 安卓