How to get a Bitmap from VectorDrawable

蹲街弑〆低调 提交于 2019-11-30 15:22:50

First of all, you cannot cast VectorDrawable to BitmapDrawable. They don't have a parent-child relationship. They both are direct subclasses of Drawable class.

Now, to get a bitmap from drawable, you will need to create a Bitmap from the drawable metadata.

Probably something like this in a separate method,

try {
    Bitmap bitmap;

    bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
} catch (OutOfMemoryError e) {
    // Handle the error
    return null;
}

I hope this helps.

Use Drawable.toBitmap() from AndroidX support library. VectorDrawable is child of Drawable.

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