如何为快捷方式制作圆形图标

How to make a round icon for shortcut

我正在尝试将 Android 快捷方式添加到应用程序中,包括动态快捷方式和图标,它们将从位图创建。现在看起来像这样:

如您所见,动态快捷方式图标中间有一个正方形图像,但我需要它占据整个图标 space,因此不会有白色背景。 代码:

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();

添加到正在加载图像的 imageView xml 文件

android:scaleType="centerCrop"

我想我找到了一种可能的解决方案,那就是使用自适应图标。它对我来说看起来有点奇怪,但嘿,只要它有效。 我已经使用了 AdaptiveIconDrawable,这里是如何做的:

  1. 我们需要将快捷方式图标的位图转换为 BitmapDrawable。
  2. 我们创建一个 AdaptiveIconDrawable 并将 BitmapDrawable 传递给它。
  3. 然后我们创建另一个位图并在其上绘制我们的 AdaptiveIconDrawable canvas,从而将 AdaptiveIconDrawable 转换回位图(我猜是自适应位图?)
  4. 最后我们使用Icon.createWithAdaptiveBitmap方法设置快捷方式图标

将位图转换为自适应位图的代码:

@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;
    }

然后你可以这样设置快捷方式的图标:

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