我正在尝试从drawable中加载一个简单的资源。我创建了一个位图,其中有一个drawable作为源:
<?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);
但他们总是返回null。如果位图xml存在且可绘制,那么返回null的原因是什么?
答案 0 :(得分:0)
原因在于Bitmaps和Drawables之间存在差异。使用
删除“位图”文件<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:src="@drawable/ball"/>
内容(留在只有<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));