我查看了多个类似的问题,虽然我的查询没有找到合适的答案。
我有一个drawable,在shape.xml中定义
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@color/bg_color" />
</shape>
我想将其转换为Bitmap对象以执行某些操作,但BitmapFactory.decodeResource()
返回null。
我正是这样做的:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);
我做错了什么? BitmapFactory.decodeResource()
是否适用于xml定义的drawables?
答案 0 :(得分:54)
由于您要加载Drawable
而不是Bitmap
,请使用以下命令:
Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);
将其变为Bitmap
:
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
答案 1 :(得分:1)
public static Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Integer width, Integer height) {
Drawable d = getResources().getDrawable(drawableId);
if (d instanceof BitmapDrawable) {
return ((BitmapDrawable) d).getBitmap();
}
if (d instanceof GradientDrawable) {
GradientDrawable g = (GradientDrawable) d;
int w = d.getIntrinsicWidth() > 0 ? d.getIntrinsicWidth() : width;
int h = d.getIntrinsicHeight() > 0 ? d.getIntrinsicHeight() : height;
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
g.setBounds(0, 0, w, h);
g.setStroke(1, Color.BLACK);
g.setFilterBitmap(true);
g.draw(canvas);
return bitmap;
}
Bitmap bit = BitmapFactory.decodeResource(getResources(), drawableId);
return bit.copy(Bitmap.Config.ARGB_8888, true);
}
//------------------------
Bitmap b = convertDrawableResToBitmap(R.drawable.myDraw , 50, 50);
答案 2 :(得分:0)
它是一个可绘制的,而不是位图。您应该使用getDrawable
代替
答案 3 :(得分:0)
您可能已将.xml
放入目录:... /drawable-24
,然后尝试将其放入... /drawable
。
它对我有用,希望这可以对某人有所帮助。