Java – Programmatically resize vectordrawable icons

Programmatically resize vectordrawable icons… here is a solution to the problem.

Programmatically resize vectordrawable icons

I’m dynamically displaying some VectorDrawable icons in my android project.
However, I can’t scale the icon in the java layer using the following 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 didn’t solve my problem.

Solution

jDrawable.setBounds does not work due to a bug in android.

One way to overcome this error 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);

This bitmap is then used to display something like the following. First convert it to BitmapDrawable

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

Similarly, in your helper function, you can return bd.

To use it on a pre-23 API, put it into build.gradle

vectorDrawables.useSupportLibrary = true 

Related Problems and Solutions