Droid Dev Stream
Part 98: LayerList drawable + conversion to a Bitmap

We can have a layer-list, which is a bunch of drawables layered upon each other. Create this in your res/drawable-mdpi/layerlist.xml (or whatever drawable dir you want).

<?xml version=”1.0” encoding=”utf-8”?>
<layer-list xmlns:android=”http://schemas.android.com/apk/res/android”>
    <item>
      <bitmap android:src=”@drawable/icon”
        android:gravity=”center” />
    </item>
    <item android:top=”20dp” android:left=”20dp”>
      <bitmap android:src=”@drawable/icon”
        android:gravity=”center” />
    </item>
</layer-list>

This is just taking the default android icon, twice, in <item> tags, with the second one being offset by 20dp.

We can now add this to a ImageView using the src attribute with @drawable/layerlist. Note the name is the same as our filename.

We can also convert this to a Bitmap to save:

Drawable d = (Drawable) getResources().getDrawable(R.drawable.layerlist);
Bitmap b = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

This get the LayerList drawable we defined above. We’re only getting this to find its height and width.

Then we create a Bitmap, with the widdth and height of our drawable. We will be writing to this Bitmap. Note the Bitmap.Config.ARGB_8888 variable. I’ve tried other Bitmap.Config fields—not all have worked. This did.

LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.layerlist);
ld.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ld.draw(new Canvas(b));  

Now we’re grabbing our LayerDrawable, i.e. the LayerList, and setting its bounds to its Drawable we grabbed before. We must set the bounds, or our bitmap won’t write.

Finally we draw that LayerDrawable, which contains our previously defined layered icons, to the Bitmap.

Now our Bitmap, b, has the our previously LayeredDrawable as a normal bitmap. We can save this if we want. And we’ll do that next.

  1. droiddevelop posted this
Blog comments powered by Disqus