Example usage for android.graphics Canvas setBitmap

List of usage examples for android.graphics Canvas setBitmap

Introduction

In this page you can find the example usage for android.graphics Canvas setBitmap.

Prototype

public void setBitmap(@Nullable Bitmap bitmap) 

Source Link

Document

Specify a bitmap for the canvas to draw into.

Usage

From source file:com.android.launcher2.AsyncTaskCallback.java

private Bitmap getWidgetPreview(ComponentName provider, int previewImage, int iconId, int cellHSpan,
        int cellVSpan, int maxWidth, int maxHeight) {
    // Load the preview image if possible
    String packageName = provider.getPackageName();
    if (maxWidth < 0)
        maxWidth = Integer.MAX_VALUE;
    if (maxHeight < 0)
        maxHeight = Integer.MAX_VALUE;

    Drawable drawable = null;/*w  w w  .  j a v a 2s . c o m*/
    if (previewImage != 0) {
        drawable = mPackageManager.getDrawable(packageName, previewImage, null);
        if (drawable == null) {
            Log.w(TAG, "Can't load widget preview drawable 0x" + Integer.toHexString(previewImage)
                    + " for provider: " + provider);
        }
    }

    int bitmapWidth;
    int bitmapHeight;
    Bitmap defaultPreview = null;
    boolean widgetPreviewExists = (drawable != null);
    if (widgetPreviewExists) {
        bitmapWidth = drawable.getIntrinsicWidth();
        bitmapHeight = drawable.getIntrinsicHeight();
    } else {
        // Generate a preview image if we couldn't load one
        if (cellHSpan < 1)
            cellHSpan = 1;
        if (cellVSpan < 1)
            cellVSpan = 1;

        BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
                .getDrawable(R.drawable.widget_preview_tile);
        final int previewDrawableWidth = previewDrawable.getIntrinsicWidth();
        final int previewDrawableHeight = previewDrawable.getIntrinsicHeight();
        bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
        bitmapHeight = previewDrawableHeight * cellVSpan;

        defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
        final Canvas c = mCachedAppWidgetPreviewCanvas.get();
        c.setBitmap(defaultPreview);
        previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
        previewDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
        previewDrawable.draw(c);
        c.setBitmap(null);

        // Draw the icon in the top left corner
        int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
        int smallestSide = Math.min(bitmapWidth, bitmapHeight);
        float iconScale = Math.min((float) smallestSide / (mAppIconSize + 2 * minOffset), 1f);

        try {
            Drawable icon = null;
            int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
            int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
            if (iconId > 0)
                icon = mIconCache.getFullResIcon(packageName, iconId);
            if (icon != null) {
                renderDrawableToBitmap(icon, defaultPreview, hoffset, yoffset, (int) (mAppIconSize * iconScale),
                        (int) (mAppIconSize * iconScale));
            }
        } catch (Resources.NotFoundException e) {
        }
    }

    // Scale to fit width only - let the widget preview be clipped in the
    // vertical dimension
    float scale = 1f;
    if (bitmapWidth > maxWidth) {
        scale = maxWidth / (float) bitmapWidth;
    }
    if (scale != 1f) {
        bitmapWidth = (int) (scale * bitmapWidth);
        bitmapHeight = (int) (scale * bitmapHeight);
    }

    Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);

    // Draw the scaled preview into the final bitmap
    if (widgetPreviewExists) {
        renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight);
    } else {
        final Canvas c = mCachedAppWidgetPreviewCanvas.get();
        final Rect src = mCachedAppWidgetPreviewSrcRect.get();
        final Rect dest = mCachedAppWidgetPreviewDestRect.get();
        c.setBitmap(preview);
        src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
        dest.set(0, 0, preview.getWidth(), preview.getHeight());

        Paint p = mCachedAppWidgetPreviewPaint.get();
        if (p == null) {
            p = new Paint();
            p.setFilterBitmap(true);
            mCachedAppWidgetPreviewPaint.set(p);
        }
        c.drawBitmap(defaultPreview, src, dest, p);
        c.setBitmap(null);
    }
    return preview;
}

From source file:com.android.launcher2.AsyncTaskCallback.java

private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale) {
    if (bitmap != null) {
        Canvas c = new Canvas(bitmap);
        c.scale(scale, scale);/*from www.  java2s  .c  om*/
        Rect oldBounds = d.copyBounds();
        d.setBounds(x, y, x + w, y + h);
        d.draw(c);
        d.setBounds(oldBounds); // Restore the bounds
        c.setBitmap(null);
    }
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

private static Intent createShortcutIntent(long did, boolean forDelete) {
    Intent shortcutIntent = new Intent(ApplicationLoader.applicationContext, OpenChatReceiver.class);

    int lower_id = (int) did;
    int high_id = (int) (did >> 32);

    TLRPC.User user = null;/*from  ww  w .ja va 2  s  . com*/
    TLRPC.Chat chat = null;
    if (lower_id == 0) {
        shortcutIntent.putExtra("encId", high_id);
        TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(high_id);
        if (encryptedChat == null) {
            return null;
        }
        user = MessagesController.getInstance().getUser(encryptedChat.user_id);
    } else if (lower_id > 0) {
        shortcutIntent.putExtra("userId", lower_id);
        user = MessagesController.getInstance().getUser(lower_id);
    } else if (lower_id < 0) {
        chat = MessagesController.getInstance().getChat(-lower_id);
        shortcutIntent.putExtra("chatId", -lower_id);
    } else {
        return null;
    }
    if (user == null && chat == null) {
        return null;
    }

    String name;
    TLRPC.FileLocation photo = null;

    if (user != null) {
        name = ContactsController.formatName(user.first_name, user.last_name);
        if (user.photo != null) {
            photo = user.photo.photo_small;
        }
    } else {
        name = chat.title;
        if (chat.photo != null) {
            photo = chat.photo.photo_small;
        }
    }

    shortcutIntent.setAction("com.tmessages.openchat" + did);
    shortcutIntent.addFlags(0x4000000);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
    addIntent.putExtra("duplicate", false);
    if (!forDelete) {
        Bitmap bitmap = null;
        if (photo != null) {
            try {
                File path = FileLoader.getPathToAttach(photo, true);
                bitmap = BitmapFactory.decodeFile(path.toString());
                if (bitmap != null) {
                    int size = AndroidUtilities.dp(58);
                    Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
                    result.eraseColor(Color.TRANSPARENT);
                    Canvas canvas = new Canvas(result);
                    BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
                            Shader.TileMode.CLAMP);
                    if (roundPaint == null) {
                        roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                        bitmapRect = new RectF();
                    }
                    float scale = size / (float) bitmap.getWidth();
                    canvas.save();
                    canvas.scale(scale, scale);
                    roundPaint.setShader(shader);
                    bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
                    canvas.drawRoundRect(bitmapRect, bitmap.getWidth(), bitmap.getHeight(), roundPaint);
                    canvas.restore();
                    Drawable drawable = ApplicationLoader.applicationContext.getResources()
                            .getDrawable(R.drawable.book_logo);
                    int w = AndroidUtilities.dp(15);
                    int left = size - w - AndroidUtilities.dp(2);
                    int top = size - w - AndroidUtilities.dp(2);
                    drawable.setBounds(left, top, left + w, top + w);
                    drawable.draw(canvas);
                    try {
                        canvas.setBitmap(null);
                    } catch (Exception e) {
                        //don't promt, this will crash on 2.x
                    }
                    bitmap = result;
                }
            } catch (Throwable e) {
                FileLog.e(e);
            }
        }
        if (bitmap != null) {
            addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
        } else {
            if (user != null) {
                if (user.bot) {
                    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                            .fromContext(ApplicationLoader.applicationContext, R.drawable.book_bot));
                } else {
                    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                            .fromContext(ApplicationLoader.applicationContext, R.drawable.book_user));
                }
            } else if (chat != null) {
                if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                            .fromContext(ApplicationLoader.applicationContext, R.drawable.book_channel));
                } else {
                    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                            .fromContext(ApplicationLoader.applicationContext, R.drawable.book_group));
                }
            }
        }
    }
    return addIntent;
}

From source file:com.android.launcher2.AsyncTaskCallback.java

private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
    Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
    final Canvas c = mCachedShortcutPreviewCanvas.get();
    if (tempBitmap == null || tempBitmap.getWidth() != maxWidth || tempBitmap.getHeight() != maxHeight) {
        tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
        mCachedShortcutPreviewBitmap.set(tempBitmap);
    } else {// w  w  w .j  a v  a2  s  .c o m
        c.setBitmap(tempBitmap);
        c.drawColor(0, PorterDuff.Mode.CLEAR);
        c.setBitmap(null);
    }
    // Render the icon
    Drawable icon = mIconCache.getFullResIcon(info);

    int paddingTop = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
    int paddingLeft = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
    int paddingRight = getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);

    int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);

    renderDrawableToBitmap(icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);

    Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
    c.setBitmap(preview);
    Paint p = mCachedShortcutPreviewPaint.get();
    if (p == null) {
        p = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
        p.setAlpha((int) (255 * 0.06f));
        //float density = 1f;
        //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
        mCachedShortcutPreviewPaint.set(p);
    }
    c.drawBitmap(tempBitmap, 0, 0, p);
    c.setBitmap(null);

    renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);

    return preview;
}

From source file:com.android.contacts.common.list.ShortcutIntentBuilder.java

/**
 * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
 * number, and if there is a photo also adds the call action icon.
 *///from   ww w  .  ja  v  a  2s .  com
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    Bitmap phoneIcon = ((BitmapDrawable) r.getDrawableForDensity(actionResId, mIconDensity)).getBitmap();

    Bitmap icon = generateQuickContactIcon(photo);
    Canvas canvas = new Canvas(icon);

    // Copy in the photo
    Paint photoPaint = new Paint();
    photoPaint.setDither(true);
    photoPaint.setFilterBitmap(true);
    Rect dst = new Rect(0, 0, mIconSize, mIconSize);

    // Create an overlay for the phone number type
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);

    if (overlay != null) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(r.getDimension(R.dimen.shortcut_overlay_text_size));
        textPaint.setColor(r.getColor(R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f, r.getColor(R.color.textColorIconOverlayShadow));

        final FontMetricsInt fmi = textPaint.getFontMetricsInt();

        // First fill in a darker background around the text to be drawn
        final Paint workPaint = new Paint();
        workPaint.setColor(mOverlayTextBackgroundColor);
        workPaint.setStyle(Paint.Style.FILL);
        final int textPadding = r.getDimensionPixelOffset(R.dimen.shortcut_overlay_text_background_padding);
        final int textBandHeight = (fmi.descent - fmi.ascent) + textPadding * 2;
        dst.set(0, mIconSize - textBandHeight, mIconSize, mIconSize);
        canvas.drawRect(dst, workPaint);

        overlay = TextUtils.ellipsize(overlay, textPaint, mIconSize, TruncateAt.END);
        final float textWidth = textPaint.measureText(overlay, 0, overlay.length());
        canvas.drawText(overlay, 0, overlay.length(), (mIconSize - textWidth) / 2,
                mIconSize - fmi.descent - textPadding, textPaint);
    }

    // Draw the phone action icon as an overlay
    Rect src = new Rect(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight());
    int iconWidth = icon.getWidth();
    dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
    canvas.drawBitmap(phoneIcon, src, dst, photoPaint);

    canvas.setBitmap(null);

    return icon;
}

From source file:com.silentcircle.contacts.list.ShortcutIntentBuilder.java

/**
 * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
 * number, and if there is a photo also adds the call action icon.
 *///from   w w w  .j  a  va 2 s  . c  om
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    Bitmap phoneIcon = ((BitmapDrawable) r.getDrawableForDensity(actionResId, mIconDensity)).getBitmap();

    Bitmap icon = generateQuickContactIcon(photo);
    Canvas canvas = new Canvas(icon);

    // Copy in the photo
    Paint photoPaint = new Paint();
    photoPaint.setDither(true);
    photoPaint.setFilterBitmap(true);
    Rect dst = new Rect(0, 0, mIconSize, mIconSize);

    // Create an overlay for the phone number type
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);

    if (overlay != null) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(r.getDimension(R.dimen.shortcut_overlay_text_size));
        textPaint.setColor(ContextCompat.getColor(mContext, R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f,
                ContextCompat.getColor(mContext, R.color.textColorIconOverlayShadow));

        final FontMetricsInt fmi = textPaint.getFontMetricsInt();

        // First fill in a darker background around the text to be drawn
        final Paint workPaint = new Paint();
        workPaint.setColor(mOverlayTextBackgroundColor);
        workPaint.setStyle(Paint.Style.FILL);
        final int textPadding = r.getDimensionPixelOffset(R.dimen.shortcut_overlay_text_background_padding);
        final int textBandHeight = (fmi.descent - fmi.ascent) + textPadding * 2;
        dst.set(0, mIconSize - textBandHeight, mIconSize, mIconSize);
        canvas.drawRect(dst, workPaint);

        overlay = TextUtils.ellipsize(overlay, textPaint, mIconSize, TruncateAt.END);
        final float textWidth = textPaint.measureText(overlay, 0, overlay.length());
        canvas.drawText(overlay, 0, overlay.length(), (mIconSize - textWidth) / 2,
                mIconSize - fmi.descent - textPadding, textPaint);
    }

    // Draw the phone action icon as an overlay
    Rect src = new Rect(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight());
    int iconWidth = icon.getWidth();
    dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
    canvas.drawBitmap(phoneIcon, src, dst, photoPaint);

    canvas.setBitmap(null);

    return icon;
}

From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java

public void save() {
    try {/*from   www  . j  ava2  s .  c o m*/
        runOnUiThread(new Runnable() {
            public void run() {
                view.addvaluestotabstable();
                view.addvaluestobom();
                if (u.isbluestacks()) {
                    //Tabs1.bluestacksimagequalitydialog(getBaseContext());
                }
            }
        });

        if (ACTION == ACTION_SHOWLAYERS) {
            ACTION = ACTION_DONOTHING;
        }

        Log.d("MULTILEVEL checked in save", String.valueOf(MULTILEVEL));
        //            if(!MULTILEVEL){
        //               Canvas canvascopy = new Canvas();
        //               Bitmap canvasbitmap=resizedbitmaponmemorycheck();
        //               canvascopy.setBitmap(canvasbitmap);
        //
        //               view.DONTSCALEORTRANSLATE = true;
        //               view.CanvasChanges(canvascopy);
        //               view.DONTSCALEORTRANSLATE = false;
        //
        //               File file = new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp]);
        //               file.mkdirs();
        //               if (file.exists())
        //                  file.delete();
        //
        //               FileOutputStream fos = new FileOutputStream(
        //                     new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp]));
        //
        //               canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        //               //canvasbitmap.recycle();
        //               try {
        //                  Log.d("trying outputstream flush and close","true");
        //                  fos.flush();
        //                  fos.close();
        //                  fos = null;
        //               } catch (IOException e) {
        //                  // TODO Auto-generated catch block
        //                  e.printStackTrace();
        //               }
        //            }else{

        //recycling original canvas

        Log.d("floorplancount", u.s(floorplancount));
        for (int x = 0; x < floorplancount; x++) {
            Log.d("floorplan count", u.s(x));
            FloorPlanView.fp = x;
            //                  view.originalbitmap = BitmapFactory.decodeFile(Tabs1.InputFloorPlanLocation[x]);
            //                  Log.d("inputfloorplan path",Tabs1.InputFloorPlanLocation[x].toString());
            //                  view.bm = view.originalbitmap;
            //                  view.bitheight = view.bm.getHeight();
            //                  view.bitwidth = view.bm.getWidth();
            view.invalidate();

            Canvas canvascopy = new Canvas();
            Bitmap canvasbitmap = resizedbitmaponmemorycheck();
            canvascopy.setBitmap(canvasbitmap);

            view.DONTSCALEORTRANSLATE = true;
            view.CanvasChanges(canvascopy);
            view.DONTSCALEORTRANSLATE = false;

            String newoutputfilestring = Tabs1.floorplanstrings.get(x).replace(Tabs1.inputfloorplandirectory,
                    Tabs1.outputfloorplandirectory);

            File file = new File(newoutputfilestring);
            file.mkdirs();
            if (file.exists())
                file.delete();

            FileOutputStream fos = new FileOutputStream(new File(newoutputfilestring));

            Log.d("outputfloorplan path", newoutputfilestring);
            canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            //canvasbitmap.recycle();
            try {
                Log.d("trying outputstream flush and close", "true");
                fos.flush();
                fos.close();
                fos = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = Tabs1.FLOORPLANPICTURESIZE;
            Bitmap bm = BitmapFactory.decodeFile(newoutputfilestring, o);

            double calcheight = (double) Tabs1.screenheight
                    * (double) Tabs1.FLOORPLANPICTUREDISPLAYPERCENTOFSCREEN / (double) 100;
            double calcwidth = (double) bm.getWidth() / (double) bm.getHeight() * (double) calcheight;

            int height = (int) calcheight;
            int width = (int) calcwidth;

            Bitmap resizedbitmap = null;

            outputfloorplanthumbnail = Bitmap.createScaledBitmap(bm, width, height, true);
            bm.recycle();
            canvasbitmap.recycle();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //writeexcel();
    //rewritewholedb();
    System.out.println("database after write db");
    try {
        Tabs1.db.showfulldblog(dbtablename);
    } catch (Throwable e) {

    }
    FINALBITMAPSCALE = 1;
}

From source file:com.zyk.launcher.AsyncTaskCallback.java

/**
 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
 * Responsibility for the bitmap is transferred to the caller.
 *///from  ww w.j  a v a2s  .  c  o  m
private Bitmap createDragOutline(View v, int padding) {
    final int outlineColor = getResources().getColor(R.color.outline_color);
    final Bitmap b = Bitmap.createBitmap(v.getWidth() + padding, v.getHeight() + padding,
            Bitmap.Config.ARGB_8888);

    Canvas mCanvas = new Canvas();
    mCanvas.setBitmap(b);
    Utils.drawDragView(v, mCanvas, padding);
    //        mOutlineHelper.applyExpensiveOutlineWithBlur(b, mCanvas, outlineColor, outlineColor);
    mCanvas.setBitmap(null);
    return b;
}

From source file:com.android.contacts.ShortcutIntentBuilder.java

/**
 * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
 * number, and if there is a photo also adds the call action icon.
 *//* w w w  .j  av  a  2 s  .  c o  m*/
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    final Drawable phoneDrawable = r.getDrawableForDensity(actionResId, mIconDensity);
    // These icons have the same height and width so either is fine for the size.
    final Bitmap phoneIcon = BitmapUtil.drawableToBitmap(phoneDrawable, phoneDrawable.getIntrinsicHeight());

    Bitmap icon = generateQuickContactIcon(photo);
    Canvas canvas = new Canvas(icon);

    // Copy in the photo
    Paint photoPaint = new Paint();
    photoPaint.setDither(true);
    photoPaint.setFilterBitmap(true);
    Rect dst = new Rect(0, 0, mIconSize, mIconSize);

    // Create an overlay for the phone number type if we're pre-O. O created shortcuts have the
    // app badge which overlaps the type overlay.
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);
    if (!BuildCompat.isAtLeastO() && overlay != null) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(r.getDimension(R.dimen.shortcut_overlay_text_size));
        textPaint.setColor(r.getColor(R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f, r.getColor(R.color.textColorIconOverlayShadow));

        final FontMetricsInt fmi = textPaint.getFontMetricsInt();

        // First fill in a darker background around the text to be drawn
        final Paint workPaint = new Paint();
        workPaint.setColor(mOverlayTextBackgroundColor);
        workPaint.setStyle(Paint.Style.FILL);
        final int textPadding = r.getDimensionPixelOffset(R.dimen.shortcut_overlay_text_background_padding);
        final int textBandHeight = (fmi.descent - fmi.ascent) + textPadding * 2;
        dst.set(0, mIconSize - textBandHeight, mIconSize, mIconSize);
        canvas.drawRect(dst, workPaint);

        overlay = TextUtils.ellipsize(overlay, textPaint, mIconSize, TruncateAt.END);
        final float textWidth = textPaint.measureText(overlay, 0, overlay.length());
        canvas.drawText(overlay, 0, overlay.length(), (mIconSize - textWidth) / 2,
                mIconSize - fmi.descent - textPadding, textPaint);
    }

    // Draw the phone action icon as an overlay
    int iconWidth = icon.getWidth();
    if (BuildCompat.isAtLeastO()) {
        // On O we need to calculate where the phone icon goes slightly differently. The whole
        // canvas area is 108dp, a centered circle with a diameter of 66dp is the "safe zone".
        // So we start the drawing the phone icon at
        // 108dp - 21 dp (distance from right edge of safe zone to the edge of the canvas)
        // - 24 dp (size of the phone icon) on the x axis (left)
        // The y axis is simply 21dp for the distance to the safe zone (top).
        // See go/o-icons-eng for more details and a handy picture.
        final int left = (int) (mIconSize - (45 * density));
        final int top = (int) (21 * density);
        canvas.drawBitmap(phoneIcon, left, top, photoPaint);
    } else {
        dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
        canvas.drawBitmap(phoneIcon, null, dst, photoPaint);
    }

    canvas.setBitmap(null);
    return icon;
}

From source file:com.android.launcher2.Workspace.java

/**
 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
 * Responsibility for the bitmap is transferred to the caller.
 *//*from   w w  w  . j a va 2  s  .c om*/
private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, boolean clipAlpha) {
    final int outlineColor = getResources().getColor(android.R.color.holo_blue_light);
    final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    canvas.setBitmap(b);

    Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight());
    float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(),
            (h - padding) / (float) orig.getHeight());
    int scaledWidth = (int) (scaleFactor * orig.getWidth());
    int scaledHeight = (int) (scaleFactor * orig.getHeight());
    Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);

    // center the image
    dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2);

    canvas.drawBitmap(orig, src, dst, null);
    mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, clipAlpha);
    canvas.setBitmap(null);

    return b;
}