以编程方式调整可缩放矢量图标的大小

3

我在安卓项目中动态展示一些VectorDrawable图标。然而,我无法使用下面的代码在Java层缩放这些图标:

VectorDrawable jDrawable = (VectorDrawable) getContext().getDrawable(nResourceID);

// resize the icon
jDrawable.setBounds(30, 30, 30, 30);

// set the icon in the button view
button.setCompoundDrawablesRelativeWithIntrinsicBounds(jDrawable, null, null, null);

注意: Android如何在程序中动态调整(缩放)XML矢量图标的大小,但该答案并未解决我的问题。


你误解了我的意思!抱歉我没有表达完整。 - Shreyash S Sarnayak
2个回答

7

jDrawable.setBounds 由于Android中的一个错误而无法工作。

克服这个问题的一种方法是将 VectorDrawable 转换为 Bitmap 并显示它。

Bitmap bitmap = Bitmap.createBitmap(jDrawable.getIntrinsicWidth(), jDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
jDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
jDrawable.draw(canvas);

然后使用这个位图(bitmap)显示像下面这样的东西。首先将其转换为BitmapDrawable
BitmapDrawable bd = new BitmapDrawable(bitmap);
buttonsetCompoundDrawablesRelativeWithIntrinsicBounds(bd, null, null, null);

在你的辅助函数中,你可以返回bd
如果要在API版本低于23的情况下使用它,请将以下代码放入build.gradle文件中。
vectorDrawables.useSupportLibrary = true 

1
总是获得预期结果! - Pratik Saluja

1

至少在 API > 21 上更容易。 假设我们有来自资源的 VectorDrawable(检索它的示例代码):

val iconResource = context.resources.getIdentifier(name, "drawable", context.packageName)
val drawable = context.resources.getDrawable(iconResource, null)

对于那个VectorDrawable,只需设置所需的大小:

drawable.setBounds(0, 0, size, size)

在按钮中显示可绘制对象:

button.setCompoundDrawables(null, drawable, null, null)

就是这样。但请注意使用setCompoundDrawables(而不是Intrinsic版本)!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接