Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overlay two images in android to set an imageview

Tags:

android

image

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); } 
like image 334
John Avatar asked Apr 29 '10 18:04

John


People also ask

How do you overlay two pictures on android?

This example demonstrates how do I overlay two images In Android to set an ImageView. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I overlay multiple images?

Open your base image in Photoshop, and add your secondary images to another layer in the same project. Resize, drag, and drop your images into position. Choose a new name and location for the file. Click Export or Save.


1 Answers

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">     <item android:drawable="@drawable/t" />     <item android:drawable="@drawable/tt" /> </layer-list> 

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.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.)

like image 83
Dan Lew Avatar answered Sep 21 '22 03:09

Dan Lew