图片的高效加载

1. Bitmap:位图

BitmapFactory.decodeFile();

BitmapFactory.decodeStream();

BitmapFactory.decodeResource();

BitmapFactory.deocdeByteArray();

其中decodeFile()和decodeResource()是间接调用decodeStream()的;

主要代码加解释:

/**
     * 利用采样率
     * @param res
     * @param resId
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public Bitmap decodeSampleBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

        // 创建BitmapFactory.Options 对象
        BitmapFactory.Options options = new BitmapFactory.Options();
        //只会解析图片的原始宽高信息,并不会去加载图片的
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeResource(res, resId, options);

        //去计算采样率
        options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);

        //从true设置为false
        options.inJustDecodeBounds = false;

        //计算完采样率,就去重新加载图片  通常采样率都会采用2的倍数
        Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);


        return bitmap;
    }


    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        //获取到当前图片的实际高度
        int height = options.outHeight;

        / //获取到当前图片的实际宽度
        int width = options.outWidth;

        int inSampleSize = 1;

        //将图片的实际宽度和高度,与需要的宽度和高度进行比较
        if (height > reqHeight || width > reqWidth) {
            int halfHeight = height / 2;
            int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize*=2;
            }
        }


        return inSampleSize;
    }

 

你可能感兴趣的:(Android基础知识)