resize vectordrawable icon programmatically

。_饼干妹妹 提交于 2019-12-10 20:27:20

问题


I am showing some VectorDrawable icon dynamically in my android project. However, I couldn't scale the icons in java layer using the below code:

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

Note: Android how to resize (scale) an xml vector icon programmatically the answer does not solve my problem.


回答1:


jDrawable.setBounds doesn't work because of a bug in android.

One way to overcome the bug is to convert VectorDrawable to Bitmap and display it.

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

Then use this bitmap to display something like below. First convert it to BitmapDrawable

BitmapDrawable bd = new BitmapDrawable(bitmap);
buttonsetCompoundDrawablesRelativeWithIntrinsicBounds(bd, null, null, null);

Also in your helper function you can return bd.

To use it on pre-23 API put this in build.gradle

vectorDrawables.useSupportLibrary = true 



回答2:


It is much easier for at least API > 21. Assume that we have VectorDrawable from resources (example code to retrieve it):

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

For that VectorDrawable just set desired size:

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

And show drawable in button:

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

That's it. But note to use setCompoundDrawables (not Intrinsic version)!



来源:https://stackoverflow.com/questions/42395036/resize-vectordrawable-icon-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!