zoukankan      html  css  js  c++  java
  • Java.lang.OutOfMemoryError处理

    此错误对于新手做项目的时候经常会发生,而且不容易处理

    默认情况下,每个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     }

    推荐一个程序员网站:

    码农网

  • 相关阅读:
    Android activity生命周期
    Android ListView用法
    Android TextWatcher的使用方法(监听ExitText的方法)
    Android EditText禁止换行键(回车键enter)
    Android 数据存储-文件读写操作
    Android Spinner组件的使用方法
    IntelliJ IDEA下maven Spring MVC配置
    MyBatis配置文件中报错:URI is not registered(Settings | Languages & Frameworks | Schemas and DTDs)
    Eclipse下创建Spring MVC web程序--非maven版
    C# 时间与时间戳互转
  • 原文地址:https://www.cnblogs.com/xqxacm/p/4859586.html
Copyright © 2011-2022 走看看