John John - 1 year ago 411
Android Question

overlay two images in android to set an imageview

I am trying to overlay two images in my app, but they seem to crash at my

line. What am I doing wrong?

private void test() {
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.t);
Bitmap mBitmap2 = BitmapFactory.decodeResource(getResources(),;
Bitmap bmOverlay = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), mBitmap.getConfig());
Canvas canvas = new Canvas();
canvas.drawBitmap(mBitmap, new Matrix(), null);
canvas.drawBitmap(mBitmap2, new Matrix(), null);

Answer Source

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />

Now set the image using that Drawable:


Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(;
LayerDrawable layerDrawable = new LayerDrawable(layers);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download