Xml 无法加载位图

Xml bitmap can't be loaded

我正在尝试从我的可绘制对象中加载一个简单的资源。我创建了一个以可绘制对象为源的位图:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:src="@drawable/ball"/>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#FF0000"/>
</shape>

我正在使用此代码加载: bitmapDrawable = BitmapFactory.decodeResource( context.getResources(), R.drawable.bitmap_ball );

但它们始终 return 为空。如果位图 xml 存在并且也可以绘制,那么这个 return 为 null 的原因是什么?

原因是Bitmaps和Drawables不同。使用

删除你的 "bitmap" 文件
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:src="@drawable/ball"/>

content(留在 drawable 文件夹中,只有带 <shape xmlns:android... 的文件,并给它们命名 ball.xml)然后添加方法

public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = 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 {
        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;
}

来自 this 回答并这样称呼它:

Bitmap bitmapDrawable  = drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.ball));