android – catch“RuntimeException:Canvas:试图画得太大……”

我有一个应用程序,它将文件文件系统绘制到屏幕,如下所示:

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,可以避免此错误

解决方法

位图的大小太大,而Bitmap对象无法处理它.因此,ImageView应该有同样的问题.解决方案:在paint.net等程序中调整图像大小,或者为位图设置固定大小并进行缩放.

在我走得更远之前,你的stacktrace链接到位图的绘图,而不是创建对象:

at android.graphics.Canvas.drawBitmap(Canvas.java:1415)

因此,您可以这样做:

Bitmap image = BitmapFactory.decodeFile(file.getPath());//loading the large bitmap is fine. 
int w = image.getWidth();//get width
int h = image.getHeight();//get height
int aspRat = w / h;//get aspect ratio
int W = [handle width management here...];//do whatever you want with width. Fixed,screen size,anything
int H = w * aspRat;//set the height based on width and aspect ratio

Bitmap b = Bitmap.createScaledBitmap(image,W,H,false);//scale the bitmap
imageView.setimageBitmap(b);//set the image view
image = null;//save memory on the bitmap called 'image'

或者,如mentioned here,您也可以使用Picasso

注意

您在堆栈跟踪来自时尝试加载的映像是213828900字节,即213mb.这可能是具有非常高分辨率的图像,因为它们的尺寸越大,它们的字节越大.

对于大图像,具有缩放的方法可能无法工作,因为它牺牲了太多的质量.由于图像很大,毕加索可能是加载它的唯一东西而不会有太大的分辨率损失.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...