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

时间:2014-06-24 14:19:30

标签: android android-drawable xml-drawable

我查看了多个类似的问题,虽然我的查询没有找到合适的答案。

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

4 个答案:

答案 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;
}

取自:How to convert a Drawable to a 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

它对我有用,希望这可以对某人有所帮助。