我有一个应用程序,它从文件系统绘制图像到屏幕,如下所示:
Bitmap image = BitmapFactory.decodeFile(file.getPath());
imageView.setImageBitmap(image);
如果图像非常大,我会看到此错误:
java.lang.RuntimeException: Canvas: trying to draw too large(213828900bytes) bitmap.
at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
...
堆栈没有到达我的代码。我怎样才能捕捉到这个错误?或者是否有更合适的方法将图像绘制到可以避免此错误的 imageView
?
最佳答案
任何应用程序允许用户选择图片作为背景或在某处绘制,它必须遇到问题,如果用户选择全景照片或大图片,您的应用程序必须强制关闭,并且您没有机会防止错误,因为您可以'不捕获异常。
好吧,我只需要捕获异常并告诉用户我们不能加载图片然后完成,使用 Picasso 或此类库来实现附加功能太多余了,android 编码很麻烦,我不想制作它更多的痛苦。
最后,我在 core.java.android.view.DisplayListCanvas 中找到了代码,其中定义了一个最大图像大小,变量为 MAX_BITMAP_SIZE
private static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB
你无法读取程序中的变量,它被定义为私有(private)的(但如果你有任何方式读取变量请告诉我),这是抛出 RuntimeException 的部分代码:
int bitmapSize = bitmap.getByteCount();
if (bitmapSize > MAX_BITMAP_SIZE) {
throw new RuntimeException(
"Canvas: trying to draw too large(" + bitmapSize + "bytes) bitmap.");
}
我只是复制上面的部分,检查我代码中位图的大小,如果它超过 100M,则向用户显示我上面提到的消息,然后完成。
如果你的情况跟我一样,希望对你有帮助。
关于android - catch "RuntimeException: Canvas: trying to draw too large...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42495741/