BitmapFactory.decodeResource()在xml drawable中定义的形状返回null

我查看了多个类似的问题,虽然我没有find正确的答案在我的查询。

我有一个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吗?

Solutions Collecting From Web of "BitmapFactory.decodeResource()在xml drawable中定义的形状返回null"

既然你想加载一个Drawable ,而不是一个Bitmap ,使用这个:

 Drawable d = getResources().getDrawable(...); 

把它变成一个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; } 

取自: 如何将Drawable转换为位图?

这是一个可绘制的,而不是一个位图。 你应该使用getDrawable来代替

 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);