此错误对于新手做项目的时候经常会发生,而且不容易处理
默认情况下,每个android程序的dailvik虚拟机的最大堆空间大小为16M
当加载的图片太多或图片过大时经常出现OOM问题
而出现此类问题最常见的情况就是当我们使用BitMap类的时候
网上解决办法很多,这里贴出感觉最有用的一种解决办法
解决办法:
1 public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,
2 int screenHight) {
3 //获取当前bitmap的宽高
4 int w = bitmap.getWidth();
5 int h = bitmap.getHeight();
6
7 Matrix matrix = new Matrix();
8 float scale = (float) screenWidth / w;
9 float scale2 = (float) screenHight / h;
10
11 // 取比例小的值 可以把图片完全缩放在屏幕内
12 scale = scale < scale2 ? scale : scale2;
13
14 // 都按照宽度scale 保证图片不变形.根据宽度来确定高度
15 matrix.postScale(scale, scale);
16 // w,h是原图的属性.
17 return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
18 }
19
20 public Bitmap optionsBitmapSize(String imagePath, int screenWidth,
21 int screenHight) {
22
23 // 设置解析图片的配置信息
24 BitmapFactory.Options options = new Options();
25 // 设置为true 不再解析图片 只是获取图片的头部信息及宽高
26 options.inJustDecodeBounds = true;
27 // 返回为null
28 BitmapFactory.decodeFile(imagePath, options);
29 // 获取图片的宽高
30 int imageWidth = options.outWidth;
31 int imageHeight = options.outHeight;
32 // 计算缩放比例
33 int scaleWidth = imageWidth / screenWidth;
34 int scaleHeight = imageHeight / screenHight;
35 // 定义默认缩放比例为1
36 int scale = 1;
37 // 按照缩放比例大的 去缩放
38 if (scaleWidth > scaleHeight & scaleHeight >= 1) {
39 scale = scaleWidth;
40 } else if (scaleHeight > scaleWidth & scaleWidth >= 1) {
41 scale = scaleHeight;
42 }
43 // 设置为true开始解析图片
44 options.inJustDecodeBounds = false;
45 // 设置图片的采样率
46 options.inSampleSize = scale;
47 // 得到按照scale缩放后的图片
48 Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
49 return bitmap;
50 }
推荐一个程序员网站:
码农网