android避免decodeResource图片时占用太大的内存

增加largeHeap="true"属性。 

android:largeHeap 
Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. 
Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory. 

To query the available memory size at runtime, use the methods getMemoryClass() or getLargeMemoryClass(). 


我们知道调用BitmapFactory.decodeResource时,如果手机屏幕的密度很大时,如果只是在hdpi放了图片, decode出来的bitmap会自动的scale放大。 而且如果按照ARGB_8888模式decode的话一个像素需要4个字节,这样343*433分辨率的图片decode大概会占用2M多内存。 所以从2方面控制,一个是禁止scale, 一个是使用ALPHA_8模式decode。注意:这里需要看看效果是否ok, 因为使用低质量的模式decode图片可能会修饰一些图片的细节。 

Java代码  收藏代码
    1. /** 
    2.  * 因为目前我们只有一套资源文件,全都放在hdpi下面,这样如果是遇到高密度手机, 系统会按照 
    3.  * scale = (float) targetDensity / density 把图片放到几倍,这样会使得在高密度手机上经常会发生OOM。 
    4.  * 
    5.  * 这个方法用来解决在如果密度大于hdpi(240)的手机上,decode资源文件被放大scale,内容浪费的问题。 
    6.  * @param resources 
    7.  * @param id 
    8.  * @return 
    9.  */  
    10. public static Bitmap decodeResource(Resources resources, int id) {  
    11.   
    12.     int densityDpi = resources.getDisplayMetrics().densityDpi;  
    13.     Bitmap bitmap;  
    14.     TypedValue value = new TypedValue();  
    15.     resources.openRawResource(id, value);  
    16.     BitmapFactory.Options opts = new BitmapFactory.Options();  
    17.     opts.inPreferredConfig = Bitmap.Config.ALPHA_8;  
    18.     if (densityDpi > DisplayMetrics.DENSITY_HIGH) {  
    19.         opts.inTargetDensity = value.density;  
    20.         bitmap = BitmapFactory.decodeResource(resources, id, opts);  
    21.     }else{  
    22.         bitmap = BitmapFactory.decodeResource(resources, id);  
    23.     }  
    24.   
    25.     return bitmap;  
    26. }  
原文地址:https://www.cnblogs.com/exmyth/p/4632311.html