tags:

views:

189

answers:

1

I am trying to overlay two images in my app, but they seem to crash at my canvas.setbitmap line. what am I doing wrong?

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

   }
+1  A: 

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="http://schemas.android.com/apk/res/android"&gt;
    <item android:drawable="@drawable/t">
    <item android:drawable="@drawable/tt">
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.drawable.layer));

Solution #2 (dynamic):

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

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

Daniel Lew
thank you, it worked!one typo though, in case someone else uses the code: LayerDrawable layers2 = new LayerDrawable(layers);testimage.setImageDrawable(layers2);
John
sorry, you mustve edited it shortly after i grabbed the code
John