xcy396
11/18/2017 - 9:32 AM

Bitmap

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by Mark Xu on 2017/11/12.
 * 高效加载 Bitmap,参考《Android 开发艺术探索》Page414
 * Site: http://xuchongyang.com
 */

public class DecodeBitmap {
    public static Bitmap decodeBitmapFromResource(Resources resources, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();

        // 加载图片,当 inJustDecodeBounds 为 true 时,只会解析图片的原始宽/高信息
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resId, options);

        // 结合目标 View 大小,计算图片采样率
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // 加载图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(resources, resId, options);
    }

    private static int calculateInSampleSize(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) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

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