首页 > 解决方案 > 有没有办法将drawable转换为ImageVector?

问题描述

我的意思是使用 vectorResource(id = ...) 以外的方法(这让我对不断调用上下文、资源和其他事物感到困惑)。

我问这个是因为我看到我们可以在不使用smthng资源的情况下制作 TextStyles、Shapes、Colors 和 Strings。

例如iconAccent = Color(context.getColor(R.color.iconAccent))

编辑 1:
我找到了 Bitmap.asImageAsset() 方法,它在我的情况下不起作用,因为矢量,但可能对某人有用。

编辑2:
我通过这种方式得到结果:

val group = ContextCompat.getDrawable(context, R.drawable.icon_group) as VectorDrawable
DrawableCompat.setTint(group, context.getColor(R.color.foregroundMain))
group = group.toBitmap().asImageBitmap()

DrawableCompat.setTint需要用主题颜色正确绘制图标(我们不需要它,vectorResource(id = ...)因为它正确地从fillColor属性中获取颜色)

但这是拐杖,如果你知道任何其他方式 - 请写下来。相信compose开发者会考虑到这个问题。

标签: androidandroid-jetpack-compose

解决方案


您可以使用此工具(Svg2Compose:https ://github.com/DenisMondon/Svg2Compose )将 Vector Drawable 转换为 ImageVector。
这样您就可以直接调用:

Icons.YOUR_ICON

代替:

vectorResource(R.drawable.your_icon)

推荐阅读