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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With