Android 高效显示大图片

     在安卓这样内存有限的平台上,内存有限,因此在加载图片时,我们按照我们需要显示的大小对原始图片再设置所需要大小。也可以根据我们所能够使用的内存大小来对图片进行解码,可以利用BitmapFactory的Options来达到这一目的:

private static int calulaeInSampleSize(BitmapFactory.Options options, int reqWidth,
   int reqHeight) {
  
  final int height = options.outHeight;
  final int width = options.outWidth; 
  int inSampleSize = 1;
  
  if(height > reqHeight || width > reqWidth) {
   
  }
  
  return inSampleSize;
 }

 

public static Bitmap decodeSampledBitmapFromResource(
   Resources paramResources, int paramInt1, int paramInt2,
   int paramInt3) {
  BitmapFactory.Options localOptions = new BitmapFactory.Options();
  localOptions.inJustDecodeBounds = true;
  BitmapFactory.decodeResource(paramResources, paramInt1, localOptions);
   localOptions.outWidth = paramInt2;
  localOptions.outHeight = paramInt3;
  localOptions.inSampleSize = 1;
  localOptions.inJustDecodeBounds = false;
  localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
  return BitmapFactory.decodeResource(paramResources, paramInt1,
    localOptions);
 }

举个例子:

用这个方法来显示一张大墙纸按照自己的分辨率

 private Bitmap mBackgroundBitmap;
 
 private Bitmap mBackBitmap;

try {
              if (mBackBitmap == null) {
           
              DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
              int winWidht = displayMetrics.widthPixels;
              int winHeight = displayMetrics.heightPixels;
                   mBackBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
                 if(mBackgroundBitmap == null ) {
                  mBackgroundBitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.default_wallpaper, winWidht, winHeight);
                 }
                
                 Canvas c = new Canvas();
                 c.setBitmap(mBackBitmap);
                 Rect src = new Rect(0, winHeight - h, winWidht, winHeight);
                 Rect dst = new Rect(0, 0, w, h);
                 c.drawBitmap(mBackgroundBitmap, src, dst, null);
             }
             mRender.setmBackBitmap(mBackBitmap);
             mRender.init(mRs, mContext.getResources(), false);
             mRender.start();
            } catch (OutOfMemoryError e){
             mBackBitmap = null;
            }

当然调用这个以后要注意处理Bitmap

mBackgroundBitmap.recycle();

mBackgroundBitmap = null;

以避免空指针和溢出内存等问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值