Android Bitmap 重用

来源:互联网 发布:mac os x sierra 编辑:程序博客网 时间:2024/06/12 12:19

当加载相同尺寸大小的图片资源时,我们不必每次都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);
    }
    
}

原创粉丝点击