Example usage for android.graphics.drawable Drawable setBounds

List of usage examples for android.graphics.drawable Drawable setBounds

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable setBounds.

Prototype

public void setBounds(int left, int top, int right, int bottom) 

Source Link

Document

Specify a bounding rectangle for the Drawable.

Usage

From source file:Main.java

public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap = null;/*from  w  w  w. j  av a2  s.com*/

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        bitmapDrawable.setAntiAlias(true);
        bitmapDrawable.setDither(true);
        bitmapDrawable.setTargetDensity(Integer.MAX_VALUE);
        if (bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:jahirfiquitiva.iconshowcase.utilities.utils.Utils.java

public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap;//from  w  w w . j a  v a 2 s.  co  m
    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if (bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }
    if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
    }
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:com.bullmobi.message.graphics.IconFactory.java

@NonNull
private static Bitmap createIcon(@NonNull Drawable drawable, int size) {
    Bitmap icon = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(icon);

    // Calculate scale ratios
    int drawableWidth = drawable.getIntrinsicWidth();
    int drawableHeight = drawable.getIntrinsicHeight();
    float ratioX = Math.min((float) drawableWidth / drawableHeight, 1f);
    float ratioY = Math.min((float) drawableHeight / drawableWidth, 1f);

    // Calculate new width and height
    int width = Math.round(size * ratioX);
    int height = Math.round(size * ratioY);
    int paddingLeft = (size - width) / 2;
    int paddingTop = (size - height) / 2;

    // Apply size and draw
    canvas.translate(paddingLeft, paddingTop);
    drawable = drawable.mutate();//from  www  .j  av a2  s. c  o m
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);

    return icon;
}

From source file:de.azapps.mirakel.helper.TaskDialogHelpers.java

@SuppressLint("NewApi")
public static void handleSubtask(final Context ctx, final Task task, final OnTaskChangedListner taskChanged,
        final boolean asSubtask) {
    final List<Pair<Long, String>> names = Task.getTaskNames();
    final CharSequence[] values = new String[names.size()];
    for (int i = 0; i < names.size(); i++) {
        values[i] = names.get(i).second;
    }/*from   ww w  . j  ava 2  s  . c o m*/
    final View v = ((Activity) ctx).getLayoutInflater().inflate(R.layout.select_subtask, null, false);
    final ListView lv = (ListView) v.findViewById(R.id.subtask_listview);
    final List<Task> tasks = Task.cursorToTaskList(
            ctx.getContentResolver().query(MirakelInternalContentProvider.TASK_URI, Task.allColumns,
                    ModelBase.ID + "=" + task.getId() + " AND " + Task.BASIC_FILTER_DISPLAY_TASKS, null, null));
    subtaskAdapter = new SubtaskAdapter(ctx, 0, tasks, task, asSubtask);
    lv.post(new Runnable() {
        @Override
        public void run() {
            lv.setAdapter(subtaskAdapter);
        }
    });
    searchString = "";
    done = false;
    content = false;
    reminder = false;
    optionEnabled = false;
    newTask = true;
    listId = SpecialList.firstSpecialSafe().getId();
    final EditText search = (EditText) v.findViewById(R.id.subtask_searchbox);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        Drawable left = ctx.getResources().getDrawable(android.R.drawable.ic_menu_search);
        Drawable right = null;
        left.setBounds(0, 0, 42, 42);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                && ctx.getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            right = ctx.getResources().getDrawable(android.R.drawable.ic_menu_search);
            right.setBounds(0, 0, 42, 42);
            left = null;
        }
        search.setCompoundDrawables(left, null, right, null);
    }
    search.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(final Editable s) {
            // Nothing
        }

        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
            // Nothing
        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
            searchString = s.toString();
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final Button options = (Button) v.findViewById(R.id.subtasks_options);
    final LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.subtask_option_wrapper);
    wrapper.setVisibility(View.GONE);
    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (optionEnabled) {
                wrapper.setVisibility(View.GONE);
            } else {
                wrapper.setVisibility(View.VISIBLE);
                final InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
            }
            optionEnabled = !optionEnabled;
        }
    });
    final ViewSwitcher switcher = (ViewSwitcher) v.findViewById(R.id.subtask_switcher);
    final Button subtaskNewtask = (Button) v.findViewById(R.id.subtask_newtask);
    final Button subtaskSelectOld = (Button) v.findViewById(R.id.subtask_select_old);
    final boolean darkTheme = MirakelCommonPreferences.isDark();
    if (asSubtask) {
        v.findViewById(R.id.subtask_header).setVisibility(View.GONE);
        switcher.showNext();
        newTask = false;
    } else {
        subtaskNewtask.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (newTask) {
                    return;
                }
                switcher.showPrevious();
                subtaskNewtask
                        .setTextColor(ctx.getResources().getColor(darkTheme ? R.color.White : R.color.Black));
                subtaskSelectOld.setTextColor(ctx.getResources().getColor(R.color.Grey));
                newTask = true;
            }
        });
        subtaskSelectOld.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!newTask) {
                    return;
                }
                switcher.showNext();
                subtaskNewtask.setTextColor(ctx.getResources().getColor(R.color.Grey));
                subtaskSelectOld
                        .setTextColor(ctx.getResources().getColor(darkTheme ? R.color.White : R.color.Black));
                if (subtaskAdapter != null) {
                    subtaskAdapter.notifyDataSetChanged();
                }
                newTask = false;
                lv.invalidateViews();
                updateListView(subtaskAdapter, task, lv, ctx);
            }
        });
    }
    final CheckBox doneBox = (CheckBox) v.findViewById(R.id.subtask_done);
    doneBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            done = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final CheckBox reminderBox = (CheckBox) v.findViewById(R.id.subtask_reminder);
    reminderBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            reminder = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final Button list = (Button) v.findViewById(R.id.subtask_list);
    list.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final List<ListMirakel> lists = ListMirakel.all(true);
            final CharSequence[] names = new String[lists.size()];
            for (int i = 0; i < names.length; i++) {
                names[i] = lists.get(i).getName();
            }
            new AlertDialog.Builder(ctx).setSingleChoiceItems(names, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    listId = lists.get(which).getId();
                    updateListView(subtaskAdapter, task, lv, ctx);
                    list.setText(lists.get(which).getName());
                    dialog.dismiss();
                }
            }).show();
        }
    });
    final CheckBox contentBox = (CheckBox) v.findViewById(R.id.subtask_content);
    contentBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            content = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final EditText newTaskEdit = (EditText) v.findViewById(R.id.subtask_add_task_edit);
    final AlertDialog dialog = new AlertDialog.Builder(ctx).setTitle(ctx.getString(R.string.add_subtask))
            .setView(v).setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    if (newTask && newTaskEdit.getText().length() > 0) {
                        newSubtask(newTaskEdit.getText().toString(), task, ctx);
                    } else if (!newTask) {
                        final List<Task> checked = subtaskAdapter.getSelected();
                        for (final Task t : checked) {
                            if (!asSubtask) {
                                if (!t.hasSubtasksLoop(task)) {
                                    task.addSubtask(t);
                                } else {
                                    ErrorReporter.report(ErrorType.TASKS_CANNOT_FORM_LOOP);
                                }
                            } else {
                                if (!task.hasSubtasksLoop(t)) {
                                    t.addSubtask(task);
                                } else {
                                    ErrorReporter.report(ErrorType.TASKS_CANNOT_FORM_LOOP);
                                }
                            }
                        }
                    }
                    if (taskChanged != null) {
                        taskChanged.onTaskChanged(task);
                    }
                    ((Activity) ctx).getWindow()
                            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                    dialog.dismiss();
                }
            }).setNegativeButton(android.R.string.cancel, dialogDoNothing).show();
    newTaskEdit.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                newSubtask(v.getText().toString(), task, ctx);
                v.setText(null);
                if (taskChanged != null) {
                    taskChanged.onTaskChanged(task);
                }
                dialog.dismiss();
            }
            return false;
        }
    });
}

From source file:org.catnut.util.CatnutUtils.java

/**
 * ?//  w  w w  .j  a  v  a2 s .co m
 *
 * @param boundPx the icon' s rectangle bound, if zero, use the default
 */
public static SpannableString text2Emotion(Context context, String key, int boundPx) {
    SpannableString spannable = new SpannableString(key);
    InputStream inputStream = null;
    Drawable drawable = null;
    try {
        inputStream = context.getAssets().open(TweetImageSpan.EMOTIONS_DIR + TweetImageSpan.EMOTIONS.get(key));
        drawable = Drawable.createFromStream(inputStream, null);
    } catch (IOException e) {
        Log.e(TAG, "load emotion error!", e);
    } finally {
        closeIO(inputStream);
    }
    if (drawable != null) {
        if (boundPx == 0) {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        } else {
            drawable.setBounds(0, 0, boundPx, boundPx);
        }
        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
        spannable.setSpan(span, 0, key.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return spannable;
}

From source file:in.shick.diode.common.Common.java

/**
 * Helper function to display a list of URLs.
 * @param theContext The current application context.
 * @param settings The settings to use regarding the browser component.
 * @param theItem The ThingInfo item to get URLs from.
 *//*from www . j a  v a  2  s.  c  o  m*/
public static void showLinksDialog(final Context theContext, final RedditSettings settings,
        final ThingInfo theItem) {
    assert (theContext != null);
    assert (theItem != null);
    assert (settings != null);
    final ArrayList<String> urls = new ArrayList<String>();
    final ArrayList<MarkdownURL> vtUrls = theItem.getUrls();
    for (MarkdownURL vtUrl : vtUrls) {
        urls.add(vtUrl.url);
    }
    ArrayAdapter<MarkdownURL> adapter = new ArrayAdapter<MarkdownURL>(theContext,
            android.R.layout.select_dialog_item, vtUrls) {
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv;
            if (convertView == null) {
                tv = (TextView) ((LayoutInflater) theContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                        .inflate(android.R.layout.select_dialog_item, null);
            } else {
                tv = (TextView) convertView;
            }

            String url = getItem(position).url;
            String anchorText = getItem(position).anchorText;
            //                        if (Constants.LOGGING) Log.d(TAG, "links url="+url + " anchorText="+anchorText);

            Drawable d = null;
            try {
                d = theContext.getPackageManager()
                        .getActivityIcon(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch (PackageManager.NameNotFoundException ignore) {
            }
            if (d != null) {
                d.setBounds(0, 0, d.getIntrinsicHeight(), d.getIntrinsicHeight());
                tv.setCompoundDrawablePadding(10);
                tv.setCompoundDrawables(d, null, null, null);
            }

            final String telPrefix = "tel:";
            if (url.startsWith(telPrefix)) {
                url = PhoneNumberUtils.formatNumber(url.substring(telPrefix.length()));
            }

            if (anchorText != null)
                tv.setText(Html.fromHtml("<span>" + anchorText + "</span><br /><small>" + url + "</small>"));
            else
                tv.setText(Html.fromHtml(url));

            return tv;
        }
    };

    AlertDialog.Builder b = new AlertDialog.Builder(
            new ContextThemeWrapper(theContext, settings.getDialogTheme()));

    DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
        public final void onClick(DialogInterface dialog, int which) {
            if (which >= 0) {
                Common.launchBrowser(settings, theContext, urls.get(which),
                        Util.createThreadUri(theItem).toString(), false, false, settings.isUseExternalBrowser(),
                        settings.isSaveHistory());
            }
        }
    };

    b.setTitle(R.string.select_link_title);
    b.setCancelable(true);
    b.setAdapter(adapter, click);

    b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        public final void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    b.show();
}

From source file:com.cleveroad.slidingtutorial.sample.renderer.DrawableRenderer.java

@Override
public void draw(@NonNull Canvas canvas, @NonNull RectF elementBounds, @NonNull Paint paint, boolean isActive) {
    Drawable drawable = isActive ? mDrawableActive : mDrawable;
    drawable.setBounds((int) elementBounds.left, (int) elementBounds.top, (int) elementBounds.right,
            (int) elementBounds.bottom);
    drawable.draw(canvas);//from  w w  w  .ja v  a  2 s  .  c o m
}

From source file:com.geekandroid.sdk.sample.TabManagerSampleFragment.java

public View getItemIndicator(String text, int resId) {
    View view = null;//from  ww  w . ja  va  2s.  c  o  m
    if (inflater == null) {
        inflater = LayoutInflater.from(getContext());
    }
    view = inflater.inflate(R.layout.item_main_tab, null);

    TextView textView = (TextView) view.findViewById(R.id.item_main_tab_view);
    textView.setText(text);

    Drawable drawable = ContextCompat.getDrawable(getContext(), resId);
    drawable.setBounds(0, 0, 60, 60);
    textView.setCompoundDrawablePadding(10);
    textView.setCompoundDrawables(null, drawable, null, null);

    return view;
}

From source file:com.example.android.supportv4.app.SharingReceiverSupport.java

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.sharing_receiver_support);

    final float density = getResources().getDisplayMetrics().density;
    final int iconSize = (int) (ICON_SIZE * density + 0.5f);

    ShareCompat.IntentReader intentReader = ShareCompat.IntentReader.from(this);

    // The following provides attribution for the app that shared the data with us.
    TextView info = (TextView) findViewById(R.id.app_info);
    Drawable d = intentReader.getCallingActivityIcon();
    d.setBounds(0, 0, iconSize, iconSize);
    info.setCompoundDrawables(d, null, null, null);
    info.setText(intentReader.getCallingApplicationLabel());

    TextView tv = (TextView) findViewById(R.id.text);
    StringBuilder txt = new StringBuilder("Received share!\nText was: ");

    txt.append(intentReader.getText());/*w ww. j a  v  a  2 s  .  com*/
    txt.append("\n");

    txt.append("Streams included:\n");
    final int N = intentReader.getStreamCount();
    for (int i = 0; i < N; i++) {
        Uri uri = intentReader.getStream(i);
        txt.append("Share included stream " + i + ": " + uri + "\n");
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(getContentResolver().openInputStream(uri)));
            try {
                txt.append(reader.readLine() + "\n");
            } catch (IOException e) {
                Log.e(TAG, "Reading stream threw exception", e);
            } finally {
                reader.close();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File not found from share.", e);
        } catch (IOException e) {
            Log.d(TAG, "I/O Error", e);
        }
    }

    tv.setText(txt.toString());
}

From source file:com.jun.elephant.ui.widget.VoteDialog.java

private void setDrawableTop(TextView textView, int resId) {
    Drawable drawable = ContextCompat.getDrawable(mContext, resId);
    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    textView.setCompoundDrawables(null, drawable, null, null);
}