get Bitmap Options - Android Graphics

Android examples for Graphics:Bitmap Option

Description

get Bitmap Options

Demo Code


//package com.java2s;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

import java.lang.reflect.Field;

public class Main {
    private static final int DECODE_BUFFER_SIZE = 16 * 1024;
    private static final int DENSITY_240 = 240;
    private static final int DENSITY_400 = 400;
    private static final float SCALE_FACTOR = 0.8f;
    private static final float SCALE_FACTOR_2 = 0.7f;
    private static final Bitmap.Config DEFAULT_BITMAP_CONFIG = Bitmap.Config.RGB_565;

    private static BitmapFactory.Options getBitmapOptions(Context context) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = true;//  w ww .  java  2s. com
        options.inPreferredConfig = DEFAULT_BITMAP_CONFIG;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[DECODE_BUFFER_SIZE];
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
            Field field = null;
            try {
                field = BitmapFactory.Options.class
                        .getDeclaredField("inNativeAlloc");
                field.setAccessible(true);
                field.setBoolean(options, true);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        int displayDensityDpi = context.getResources().getDisplayMetrics().densityDpi;
        float displayDensity = context.getResources().getDisplayMetrics().density;
        int density = 0;
        if (displayDensityDpi > DENSITY_240
                && displayDensityDpi <= DENSITY_400
                && displayDensity > 1.5f) {
            density = (int) (displayDensityDpi * SCALE_FACTOR);
        } else if (displayDensityDpi > DENSITY_400 && displayDensity > 2.5f) {
            density = (int) (displayDensityDpi * SCALE_FACTOR_2);
        }
        if (density == 0)
            return options;
        options.inDensity = density;
        options.inTargetDensity = density;
        return options;
    }
}

Related Tutorials