Java 以编程方式调整矢量绘图图标的大小
我在我的android项目中动态显示了一些矢量绘图图标。 但是,我无法使用以下代码缩放java层中的图标:Java 以编程方式调整矢量绘图图标的大小,java,android,android-vectordrawable,Java,Android,Android Vectordrawable,我在我的android项目中动态显示了一些矢量绘图图标。 但是,我无法使用以下代码缩放java层中的图标: VectorDrawable jDrawable = (VectorDrawable) getContext().getDrawable(nResourceID); // resize the icon jDrawable.setBounds(30, 30, 30, 30); // set the icon in the button view button.setCompoundDr
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);
注意:答案并不能解决我的问题。
jDrawable.setBounds
无法工作,因为android中有一个bug
克服该缺陷的一种方法是将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);
然后使用此位图
显示如下内容。首先将其转换为BitmapDrawable
BitmapDrawable bd = new BitmapDrawable(bitmap);
buttonsetCompoundDrawablesRelativeWithIntrinsicBounds(bd, null, null, null);
在助手函数中,还可以返回bd
要在23之前的API上使用它,请将其放入build.gradle
vectorDrawables.useSupportLibrary = true
至少API>21时,这要容易得多。 假设我们有VectorDrawable来自资源(检索它的示例代码): 对于该VectorDrawable,只需设置所需的大小:
drawable.setBounds(0, 0, size, size)
并显示可缩进按钮:
button.setCompoundDrawables(null, drawable, null, null)
就这样。但请注意使用setCompoundDrawables(非固有版本) 你误会我了!抱歉不完整。总是得到预期的结果!
button.setCompoundDrawables(null, drawable, null, null)