Android Bitmap 重用

本文介绍了一种在Android应用中通过复用Bitmap来优化图片加载的方法,避免了频繁创建Bitmap对象导致的内存消耗和GC开销。通过使用BitmapFactory.Options配置参数inBitmap,可以将新图片的内容解码到一个预先分配的Bitmap缓存中,实现图片资源的高效利用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当加载相同尺寸大小的图片资源时,我们不必每次都create一个新的Bitmap,可以这样:


创建一个空的Bitmap作为cache,加载同尺寸时重用这个Bitmap.


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

ops.inBitmap = cache;

ops.inSampleSize = 1;


Bitmap newPixel=BitmapFactory.decodeResource(getResources(), lastImgRes, ops);


此时newPixel equals cache !BitmapFactory解码新的内容填充到我们的cache。


下面有个小Demo供大家参考:


public class Test extends Activity {
    private Bitmap buffer;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(new ReuseBitmapView(this));


        Point size = getSize(R.drawable.img1);


        buffer = Bitmap.createBitmap(
                size.x,
                size.y,
                Bitmap.Config.ARGB_8888
        );


    }




    private class ReuseBitmapView extends View {
        private int lastImgRes;


        public ReuseBitmapView(Context context) {
            super(context);
        }


        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {


                BitmapFactory.Options ops = new BitmapFactory.Options();
                ops.inBitmap = buffer;
                ops.inSampleSize = 1;


                lastImgRes = (lastImgRes == R.drawable.img1)
                        ? R.drawable.img2
                        : R.drawable.img1;


                decodeResource(getResources(), lastImgRes, ops);


                invalidate();
            }


            return true;
        }


        @Override
        protected void onDraw(Canvas canvas) {
            RectF dst = new RectF(0, 0, getWidth(), getHeight());
            canvas.drawBitmap(buffer, null, dst, null);
        }
    }


    private Point getSize(int imgRes) {
        BitmapFactory.Options ops = new BitmapFactory.Options();
        ops.inJustDecodeBounds = true;


        decodeResource(getResources(), imgRes, ops);


        return new Point(ops.outWidth, ops.outHeight);
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值