尝试在空对象引用上调用虚拟方法 'boolean android.graphics.Bitmap.isRecycled()'

Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference

我收到 R.drawable.diamond 的错误,那是一个 .xml 文件。如果我用 .png 文件替换它,我不会收到任何错误。所以也许我使用了错误的命令。

R.drawable.diamond.xml

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

    <path
        android:fillColor="#FF5722"
        android:pathData="M 5,5 95,5 95,95 5,95 z"
        android:strokeAlpha="1"
        android:strokeColor="#FFFFFF"
        android:strokeLineCap="butt"
        android:strokeLineJoin="round"
        android:strokeWidth="4"/>

    <path
        android:fillColor="#8BC34A"
        android:pathData="m 50,30 l 20,20 -20,20 -20,-20 z"
        android:strokeAlpha="1"
        android:strokeColor="#FFFFFF"
        android:strokeLineCap="butt"
        android:strokeLineJoin="round"
        android:strokeWidth="4"/>

</vector>

GameView.java

public class GameView extends View {

    private final Bitmap diamond;
    private Paint paint = new Paint();
    private Canvas canvas = new Canvas();

    public GameView(Context context) {
        super(context);
        diamond = BitmapFactory.decodeResource(getResources(),R.drawable.diamond);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(diamond,0,0,null);
    }

}

矢量没有与之关联的位图。 这是错误的主要原因

但是如果你仍然想实现这个,你可以这样做来获得 Bitmap

private Bitmap getBitmapFromVector(Context context, int vectorDrawableRes) {
    Drawable drawable = context.getResources().getDrawable(vectorDrawableRes);
    Canvas canvas = new Canvas();
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    canvas.setBitmap(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);

    return bitmap;
}

这是一个例子:

Bitmap drawableBitmap = getBitmapFromVector(context, R.drawable.diamond);