Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

android - BitmapFactory.decodeResource() returns null for shape defined in xml drawable

I looked through multiple similar questions, although I haven't found a proper answer to my issue.

I have a drawable, defined in 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>

I want to convert it to Bitmap object in order to perform some operations, but BitmapFactory.decodeResource() returns null.

This is how I'm doing it:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);

What am I doing wrong? Is BitmapFactory.decodeResource() applicable for xml defined drawables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you want to load a Drawable, not a Bitmap, use this:

Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);

To turn it into a 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;
}

Taken from: How to convert a Drawable to a Bitmap?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...