繁体   English   中英

以编程方式调整vectordrawable图标

[英]resize vectordrawable icon programmatically

我在我的android项目中动态显示一些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矢量图标的答案并不能解决我的问题。

由于android中的错误, jDrawable.setBounds不起作用。

克服该错误的一种方法是将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

要在23之前的API上使用它,请将它放在build.gradle

vectorDrawables.useSupportLibrary = true 

至少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)

并在按钮中显示drawable:

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

而已。 但请注意使用setCompoundDrawables(不是内在版本)!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM