How to make a round icon for shortcut

884 Views Asked by At

I'm trying to add Android shortcuts into the application, including dynamic shortcuts and icons for them will be created from bitmaps. Right now it looks like this:

enter image description here

As you can see, the dynamic shortcut icons have a square image in center, but I need it to take all space of an icon, so there would be no white background. The code:

Bitmap interlocutorAvatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_conference);
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(context, peer.getId())
                        .setLongLabel("Dynamic shortcut")
                        .setShortLabel("Dynamic")
                        .setIcon(Icon.createWithBitmap(interlocutorAvatar))
                        .setIntent(new Intent(Intent.ACTION_VIEW).setClass(context, VCEngine.appInfo().getActivity(ActivitySwitcher.ActivityType.CHAT))
                                .putExtra(CustomIntent.EXTRA_PEER_ID, peer.getId())
                                .putExtra(CustomIntent.EXTRA_CHAT_ID, peer.getId()))
                        .build();
2

There are 2 best solutions below

0
On BEST ANSWER

I think I've found one possible solution, and that is to use adaptive icons. It looks a little bit weird to me, but hey as long as it works. I've used AdaptiveIconDrawable and here is how to do it:

  1. We need to convert our Bitmap for shortcut icon to BitmapDrawable.
  2. We create a AdaptiveIconDrawable and pass BitmapDrawable to it.
  3. Then we create another bitmap and draw our AdaptiveIconDrawable on it's canvas, thus converting AdaptiveIconDrawable back into Bitmap (Adaptive Bitmap I guess?)
  4. And finally we use Icon.createWithAdaptiveBitmap method to set short cut Icon

The code to convert bitmap to Adaptive Bitmap:

@RequiresApi(api = Build.VERSION_CODES.O)
    public static Bitmap convertBitmapToAdaptive(Bitmap bitmap, Context context) {
        Drawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
        AdaptiveIconDrawable drawableIcon = new AdaptiveIconDrawable(bitmapDrawable, bitmapDrawable);
        Bitmap result = Bitmap.createBitmap(drawableIcon.getIntrinsicWidth(), drawableIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        drawableIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawableIcon.draw(canvas);
        return result;
    }

Then you could set the Icon of your shortcut like this :

setIcon(Icon.createWithAdaptiveBitmap(convertBitmapToAdaptive(yourBitmap, context)))
1
On

Add to the imageView that are loading the images in your xml file

android:scaleType="centerCrop"