异常log: Fatal Exception: java.lang.RuntimeException Canvas: trying to draw too large(111590328bytes) bitmap. 这里有个疑惑这个size到底是怎么限制的呢,先了解bitmap占用内存的计算方式: 以Bitmap默认采用的色彩模式Bitmap.Config.ARGB_8888为例;在该模式中一共有四个通道,其中A表示Alpha,R表示Red,G表示Green,B表示Blue;并且这四个通道每个各占8位即一个字节,所以合起来共计4个字节。 即 bitmap占用内存 = width x height x 4 第二个问题,这个size的阈值是多少呢,查看文档找到了这个方法:
1 private static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB 2 3 @Override 4 protected void throwIfCannotDraw(Bitmap bitmap) { 5 super.throwIfCannotDraw(bitmap); 6 int bitmapSize = bitmap.getByteCount(); 7 if (bitmapSize > MAX_BITMAP_SIZE) { 8 throw new RuntimeException( 9 "Canvas: trying to draw too large(" + bitmapSize +"bytes) bitmap."); 10 } 11 }
这样就能在使用中限制bitmap的大小 防止崩溃了
1 //检查是否需要压缩 2 int width = r.getWidth(); 3 int height = r.getHeight(); 4 int inSampleSize = 1; 5 int max = 100 * 1024 * 1024; 6 while (width * height * 4 / inSampleSize > max){ 7 inSampleSize *= 2; 8 } 9 if (inSampleSize > 1){ 10 Matrix m2 = new Matrix(); 11 m2.setScale(1 / (float)inSampleSize , 1 / (float)inSampleSize); 12 r = Bitmap.createBitmap(r,0,0,width,height,m2,false); 13 }
标签:inSampleSize,height,draw,int,bitmap,large,Bitmap From: https://www.cnblogs.com/mrhan9941/p/16732028.html