2014-09-24 107 views
0

我使用小资源图像(最大25kb,最大256x256)并使用毕加索从互联网加载一些较大的图像。毕加索装载从未失败,直到现在。但是资源图像加载有时会。OutOfMemoryError虽然我缩小了位图

对于我使用(setBitmap)附加代码资源的图像,但尽管我下来缩放图像,在某些设备上我的应用程序仍然调用BitmapFactory.decodeResource时产生OutOfMemoryError。有没有人有一个想法,在哪里看下?

private static void setBitmap(final ImageView iv, final int resId) 
{ 
    iv.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() 
    { 
     public boolean onPreDraw() 
     { 
      iv.getViewTreeObserver().removeOnPreDrawListener(this); 
      iv.setImageBitmap(decodeSampledBitmapFromResource(iv.getContext().getResources(), resId, iv.getMeasuredWidth(), iv.getMeasuredHeight())); 
      return true; 
     } 
    }); 
} 

private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int w, int h) 
{ 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

    options.inSampleSize = calculateInSampleSize(options, w, h); 

    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

private static int calculateInSampleSize(BitmapFactory.Options options, int w, int h) 
{ 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > h || width > w) 
    { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 

     while ((halfHeight/inSampleSize) > h && (halfWidth/inSampleSize) > w) 
     { 
      inSampleSize *= 2; 
     } 
    } 

    L.d(ImageTools.class, "inSampleSize | height | width: " + inSampleSize + " | " + height + " | " + width); 

    return inSampleSize; 
} 

回答

0

您可以在清单中使用android:largeHeap="true"作为最后一个选项。 但是,我不建议这样做,因为它可以让你的应用程序变得缓慢。

相关问题