Resize Vectordrawable Icon Programmatically
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 = (Vecto
Solution 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.
Bitmapbitmap= Bitmap.createBitmap(jDrawable.getIntrinsicWidth(), jDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(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
BitmapDrawablebd=newBitmapDrawable(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
Solution 2:
It is much easier for at least API > 21. Assume that we have VectorDrawable from resources (example code to retrieve it):
valiconResource= context.resources.getIdentifier(name, "drawable", context.packageName)
valdrawable= 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)!
Post a Comment for "Resize Vectordrawable Icon Programmatically"