Example usage for android.graphics BitmapFactory decodeResource

List of usage examples for android.graphics BitmapFactory decodeResource

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeResource.

Prototype

public static Bitmap decodeResource(Resources res, int id, Options opts) 

Source Link

Document

Synonym for opening the given resource and calling #decodeResourceStream .

Usage

From source file:Main.java

public static Bitmap decode(Resources res, int resId, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//  www  .  j  a v a  2 s  .  c  o m
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

From source file:Main.java

public static SpannableString toSpannableString(Context context, String text, SpannableString spannableString) {

    int start = 0;
    Pattern pattern = Pattern.compile("\\\\ue[a-z0-9]{3}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        String faceText = matcher.group();
        String key = faceText.substring(1);
        BitmapFactory.Options options = new BitmapFactory.Options();
        //         options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                context.getResources().getIdentifier(key, "drawable", context.getPackageName()), options);
        ImageSpan imageSpan = new ImageSpan(context, bitmap);
        int startIndex = text.indexOf(faceText, start);
        int endIndex = startIndex + faceText.length();
        if (startIndex >= 0)
            spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        start = (endIndex - 1);//  w  w w  .j  a v  a 2  s. com
    }

    return spannableString;
}

From source file:lb.themike10452.game.Rendering.Animation.SpriteSheet.java

/**
 * @param spriteSheetResId resId of the bitmap containing the sprites
 * @param dataAsset        name of the json data map file located in assets folder
 *//*from w  w w.  ja  va  2  s . c  o m*/
public SpriteSheet(Resources resources, int spriteSheetResId, AssetManager assets, String dataAsset) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap = BitmapFactory.decodeResource(resources, spriteSheetResId, options);
    mSpriteMap = new HashMap<>();
    try {
        JSONArray array = new JSONArray(Utils.readAsset(assets, dataAsset));
        int length = array.length();
        JSONObject obj;
        String name;
        int x, y, w, h;
        for (int i = 0; i < length; i++) {
            obj = array.getJSONObject(i);
            name = obj.getString("name");
            x = obj.getInt("x");
            y = obj.getInt("y");
            w = obj.getInt("width");
            h = obj.getInt("height");
            mSpriteMap.put(name, new Sprite(x, y, w, h));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    DRAW_SCALE = resources.getDisplayMetrics().scaledDensity;
}

From source file:MainActivity.java

public Bitmap loadSampledResource(int imageID, int targetHeight, int targetWidth) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//w  w  w  . ja va 2  s  . c  om
    BitmapFactory.decodeResource(getResources(), imageID, options);
    final int originalHeight = options.outHeight;
    final int originalWidth = options.outWidth;
    int inSampleSize = 1;
    while ((originalHeight / (inSampleSize * 2)) > targetHeight
            && (originalWidth / (inSampleSize * 2)) > targetWidth) {
        inSampleSize *= 2;
    }
    options.inSampleSize = inSampleSize;
    options.inJustDecodeBounds = false;
    return (BitmapFactory.decodeResource(getResources(), imageID, options));
}

From source file:Main.java

private static Bitmap getMutableBitmap(Resources res, int id) {
    return BitmapFactory.decodeResource(res, id, getMutableOption());
}

From source file:br.com.bioscada.apps.biotracks.fragments.ChooseActivityTypeDialogFragment.java

public static Dialog getDialog(final Activity activity, final String category,
        final ChooseActivityTypeCaller caller) {
    View view = activity.getLayoutInflater().inflate(R.layout.choose_activity_type, null);
    GridView gridView = (GridView) view.findViewById(R.id.choose_activity_type_grid_view);
    final View weightContainer = view.findViewById(R.id.choose_activity_type_weight_container);

    TextView weightLabel = (TextView) view.findViewById(R.id.choose_activity_type_weight_label);
    weightLabel.setText(PreferencesUtils.isMetricUnits(activity) ? R.string.description_weight_metric
            : R.string.description_weight_imperial);

    final TextView weight = (TextView) view.findViewById(R.id.choose_activity_type_weight);

    List<Integer> imageIds = new ArrayList<Integer>();
    for (String iconValue : TrackIconUtils.getAllIconValues()) {
        imageIds.add(TrackIconUtils.getIconDrawable(iconValue));
    }//from   w  w  w.  j  a v  a 2 s .c o  m

    Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_track_airplane, options);
    int padding = 32;
    int width = options.outWidth + 2 * padding;
    int height = options.outHeight + 2 * padding;
    gridView.setColumnWidth(width);

    final ChooseActivityTypeImageAdapter imageAdapter = new ChooseActivityTypeImageAdapter(activity, imageIds,
            width, height, padding);
    gridView.setAdapter(imageAdapter);

    final String weightValue = StringUtils.formatWeight(PreferencesUtils.getWeightDisplayValue(activity));
    final AlertDialog alertDialog = new AlertDialog.Builder(activity)
            .setNegativeButton(R.string.generic_cancel, null)
            .setPositiveButton(R.string.generic_ok, new Dialog.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean newWeight = false;
                    if (weightContainer.getVisibility() == View.VISIBLE) {
                        String newValue = weight.getText().toString();
                        if (!newValue.equals(weightValue)) {
                            newWeight = true;
                            PreferencesUtils.storeWeightValue(activity, newValue);
                        }
                    }
                    int selected = imageAdapter.getSelected();
                    caller.onChooseActivityTypeDone(TrackIconUtils.getAllIconValues().get(selected), newWeight);
                }
            }).setTitle(R.string.track_edit_activity_type_hint).setView(view).create();
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            int position = getPosition(activity, category);
            alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(position != -1);
            if (position != -1) {
                imageAdapter.setSelected(position);
                imageAdapter.notifyDataSetChanged();
            }
            updateWeightContainer(weightContainer, position);
            weight.setText(weightValue);
            DialogUtils.setDialogTitleDivider(activity, alertDialog);
        }
    });

    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
            imageAdapter.setSelected(position);
            imageAdapter.notifyDataSetChanged();
            updateWeightContainer(weightContainer, position);
        }
    });
    return alertDialog;
}

From source file:com.example.propertylist.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_project_sales_list);

    ImageView mImageView = new ImageView(this);

    DisplayMetrics metrics;// w  w  w  .  ja v  a2s.c om
    int mScreenWidth;
    int mScreenHeight;

    api_key = getResources().getString(R.string.key);

    metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    mScreenWidth = metrics.widthPixels;
    mScreenHeight = metrics.heightPixels;

    if (mScreenWidth >= minScreenwidth) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (mScreenWidth >= minLandScreenwidth) {
                largeScreen = true;

            }
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (mScreenHeight > minLandScreenwidth) {
                largeScreen = true;
            }
        }
    } else {
        largeScreen = false;
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.id.daft_logo_image, options);

    mImageView.setImageBitmap( // ensure image size is 100 x 100.
            decodeSampledBitmapFromResource(getResources(), R.id.daft_logo_image, 100, 100));

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideProgressDialog();
            startListActivity();
        }
    };
}

From source file:com.example.propertylist.MainActivity.java

private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/* w  w w.  j a  v  a 2s  .  co  m*/
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

From source file:com.campusconnect.GoogleSignInActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google);

    rootView = (LinearLayout) findViewById(R.id.main_layout);

    BitmapFactory.Options bm_opts = new BitmapFactory.Options();
    bm_opts.inScaled = false;//from w w  w . ja  v  a 2  s. c  om
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_portrait_two, bm_opts);
    BitmapDrawable background = new BitmapDrawable(bitmap);
    rootView.setBackground(background);

    iv_branchProfileImage = (ImageView) findViewById(R.id.branch_profile_image);
    tv_branchUserName = (TextView) findViewById(R.id.branch_tv_username);

    try {
        String photourl = Branch.getInstance().getLatestReferringParams().getString("photourl");

        if (photourl.isEmpty()) {
            iv_branchProfileImage.setImageResource(R.mipmap.ccnoti);
        } else {
            Picasso.with(GoogleSignInActivity.this).load(photourl).error(R.mipmap.ic_launcher)
                    .memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE)
                    .placeholder(R.mipmap.ccnoti).into(iv_branchProfileImage);
        }
        tv_branchUserName.setText(Branch.getInstance().getLatestReferringParams().getString("profileName") + " "
                + "is Waiting For You");
        iv_branchProfileImage.setVisibility(View.VISIBLE);
        tv_branchUserName.setVisibility(View.VISIBLE);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (!getIntent().hasExtra("logout")) {
        if (getSharedPreferences("CC", MODE_PRIVATE).contains("profileId")) {
            Intent home = new Intent(GoogleSignInActivity.this, HomeActivity2.class);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(home);
            finish();
        }
    }
    firebaseAnalytics = FirebaseAnalytics.getInstance(this);
    // Views
    //        mStatusTextView = (TextView) findViewById(R.id.status);
    //        mDetailTextView = (TextView) findViewById(R.id.detail);
    // Button listeners
    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.sign_out_button).setOnClickListener(this);
    findViewById(R.id.disconnect_button).setOnClickListener(this);
    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
    // [END config_signin]
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
    // [START initialize_auth]
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
    // [START auth_state_listener]
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // [START_EXCLUDE]
            updateUI(user);
            // [END_EXCLUDE]
        }
    };
    // [END auth_state_listener]
}

From source file:com.amachikhin.vkmachikhin.utils.image_cache.ImageResizer.java

/**
 * Decode and sample down a bitmap from resources to the requested width and height.
 *
 * @param res       The resources object containing the image data
 * @param resId     The resource id of the image data
 * @param reqWidth  The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @param cache     The ImageCache used to find candidate bitmaps for use with inBitmap
 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions
 * that are equal to or greater than the requested width and height
 *///  ww w . j  a  va 2 s . co  m
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight,
        ImageCache cache) {

    // BEGIN_INCLUDE (read_bitmap_dimensions)
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // END_INCLUDE (read_bitmap_dimensions)

    // If we're running on Honeycomb or newer, try to use inBitmap
    addInBitmapOptions(options, cache);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}