androidxmlbitmapaliasbitmapdrawable

Are there any alternatives to getting a bitmap from XML other than using BitmapDrawable


I'm currently using BitmapDrawable in my app, but unfortunately, this implementation seems somewhat broken in Lollipop (It worked OK prior to LP, there's a separarte question regarding that issue).

So, OK, I have an XML file which is basically this:

backgrounds.xml

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/backgrounds_xlarge" />

The above is an XML file (Alias), that points to an actual png file.

In my code I'm getting the bitmap like this:

Code

BitmapDrawable bd = (BitmapDrawable) view.getResources().getDrawable(R.drawable.backgrounds);
backgrounds = bd.getBitmap();

This question is to ask if there is an alternative way to get this bitmap? Please note that BitmapFactory is no good to me as I must be able to get this bitmap via the xml alias shown above.

I've read the Offical docs on creating XML Aliases but unfortunately, they are somewhat lacking when it comes to explaining how to get access to the bitmap.

Any help or suggestions appreciated.


Solution

  • Here's another way to get a Bitmap from a BitmapDrawable, using a Canvas:

        BitmapDrawable bd = (BitmapDrawable) view.getResources().getDrawable(R.drawable.backgrounds);
        Bitmap backgrounds = Bitmap.createBitmap(bd.getIntrinsicWidth(), bd.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(backgrounds); 
        bd.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        bd.draw(canvas);