The question is a bit old but if it can help somebody, I have an answer based on this one.
The idea is to get the vector drawable using:
Drawable drawable = AppCompatDrawableManager.get().getDrawable(context, R.drawable.my_drawable);
Then we get the Bitmap from this Drawable directly with the size we want to keep the quality. Then, because we have a bitmap we can draw it where we want.
Note: In the defaultConfig section of your build.gradle, don't forget to put this line for retro-compatibility:
vectorDrawables.useSupportLibrary = true
Here is the code to get the Bitmap from the Drawable:
/**
* Extract the Bitmap from a Drawable and resize it to the expectedSize conserving the ratio.
*
* @param drawable Drawable used to extract the Bitmap. Can be null.
* @param expectSize Expected size for the Bitmap. Use {@link #DEFAULT_DRAWABLE_SIZE} to
* keep the original {@link Drawable} size.
* @return The Bitmap associated to the Drawable or null if the drawable was null.
* @see <html><a href="https://stackoverflow.com/a/10600736/1827254">Stackoverflow answer</a></html>
*/
public static Bitmap getBitmapFromDrawable(@Nullable Drawable drawable, int expectSize) {
Bitmap bitmap;
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if (bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
float ratio = (expectSize != DEFAULT_DRAWABLE_SIZE)
? calculateRatio(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), expectSize)
: 1f;
int width = (int) (drawable.getIntrinsicWidth() * ratio);
int height = (int) (drawable.getIntrinsicHeight() * ratio);
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* Calculate the ratio to multiply the Bitmap size with, for it to be the maximum size of
* "expected".
*
* @param height Original Bitmap height
* @param width Original Bitmap width
* @param expected Expected maximum size.
* @return If height and with equals 0, 1 is return. Otherwise the ratio is returned.
* The ration is base on the greatest side so the image will always be the maximum size.
*/
public static float calculateRatio(int height, int width, int expected) {
if (height == 0 && width == 0) {
return 1f;
}
return (height > width)
? expected / (float) width
: expected / (float) height;
}