Search code examples
androidandroid-support-libraryandroid-vectordrawable

VectorDrawable to Bitmap: Bitmap.setHasAlpha(boolean)' on a null object reference


I'm trying to get Bitmap from VectorDrawable (xml image):

VectorDrawable vectorDrawable = (VectorDrawable) ContextCompat.getDrawable(mContext, R.drawable.test);

Bitmap bitmap = UtilMethods.getBitmapFromVector(vectorDrawable);

But app crashes on Bitmap.createBitmap method with Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference error

    public static Bitmap getBitmapFromVector(VectorDrawable vectorDrawable) {
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);
        return bitmap;
    }

p.s.

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'

here some simple xml drawable (comma symbol)

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="16000dp"
    android:height="16000dp"
    android:viewportWidth="16000"
    android:viewportHeight="16000">


    <path
        android:fillColor="#040607"
        android:strokeWidth="1"
        android:pathData="M3637 11910 l486 -730 484 0 c265 0 483 3 483 8 0 4 -130 331 -288 727 l-288 720
-682 3 -682 2 487 -730z" />

</vector>

I tried every method from Getting Bitmap from vector drawable All of them fails on this .createBitmap method

seems to be

android:width="16000dp"
android:height="16000dp"
android:viewportWidth="16000"
android:viewportHeight="16000">

are to big values...

I've added not full xml, there are more path tags, so it's not just comma symbol with such big values:)

I tried to reduce values to 2000 (e.g.) and app stopped crashing, but it ruined my image

I made vector drawable from svg using http://inloop.github.io/svg2android/


Solution

  • change

    android:width="16000dp"
    android:height="16000dp"
    

    to

    android:width="24dp"
    android:height="24dp"
    

    don't need to chagne:

    android:viewportWidth="16000"
    android:viewportHeight="16000">