How to get a Bitmap from VectorDrawable

前端 未结 2 1469
小鲜肉
小鲜肉 2021-01-02 18:33

I\'m still trying to solve the problem I\'ve had since a couple of days ago and I still have not found a solution. However, I am getting there step by step. Now I h

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-02 19:00

    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.

提交回复
热议问题