背景图像内存大小

时间:2012-03-19 13:08:05

标签: android memory-management

所以我为我的活动获得了这个背景图片。它是480x800 png。 它有一个渐变,因此存在条带的危险,这就是为什么我使99%不透明以强制最佳的颜色模式。

在我的设备上,甚至在HTC魔术上这都没有问题。

但是,在默认的1.6模拟器上,我出现内存不足错误。该怎么办? 后台在代码中设置:

bgView.setImageResource(R.drawable.baby_pink_solid);

将最大VM堆设置为192并将设备ram大小设置为256似乎不是解决方案。

2 个答案:

答案 0 :(得分:0)

尝试使用此代码缩放任何位图:

 public class ImageScale 
 {
/**
 * Decodes the path of the image to Bitmap Image.
 * @param imagePath : path of the image.
 * @return Bitmap image.
 */
 public Bitmap decodeImage(String imagePath)
 {  
     Bitmap bitmap=null;
     try
     {

         File file=new File(imagePath);
         BitmapFactory.Options o = new BitmapFactory.Options();
         o.inJustDecodeBounds = true;

         BitmapFactory.decodeStream(new FileInputStream(file),null,o);
         final int REQUIRED_SIZE=200;
         int width_tmp=o.outWidth, height_tmp=o.outHeight;

         int scale=1;
         while(true)
         {
             if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
             break;
             width_tmp/=2;
             height_tmp/=2;
             scale*=2;  
         }  

         BitmapFactory.Options options=new BitmapFactory.Options();

         options.inSampleSize=scale;
         bitmap=BitmapFactory.decodeStream(new FileInputStream(file), null, options);

     }  
     catch(Exception e) 
     {  
         bitmap = null;
     }      
     return bitmap; 
 }

 /**
  * Resizes the given Bitmap to Given size.
  * @param bm : Bitmap to resize.
  * @param newHeight : Height to resize.
  * @param newWidth : Width to resize.
  * @return Resized Bitmap.
  */
 public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) 
 {

    Bitmap resizedBitmap = null;
    try
    {
        if(bm!=null)
        {
            int width = bm.getWidth();
            int height = bm.getHeight();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // create a matrix for the manipulation
            Matrix matrix = new Matrix();
            // resize the bit map
            matrix.postScale(scaleWidth, scaleHeight);
            // recreate the new Bitmap
resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,       true);
 // resizedBitmap = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
        }
    }
    catch(Exception e)
    {
        resizedBitmap = null;
    }

    return resizedBitmap;
} 

 }

答案 1 :(得分:0)

尝试在代码中访问位图,然后通过setImageBitmap()进行设置。如果您在代码中解码位图时得到OOM,那么这就是您从setImageResource()获取它的原因。

我发现位图在Android上处理起来很棘手,使用它们时一定要小心!

另外,请查看@Sadeshkumar Periyasamy的答案,这对于解码位图或更大尺寸的设备来说非常有用,因为这些设备没有当今设备那么强大的功能。

相关问题