Search code examples
androidmergedrawable

Maps: merging multiple different-size drawables


I have a problem. I need to merge two different sized pictures (drawables). The idea is to have a picture of someone (loaded dynamically) that is 100x100px and have a transparent background that is bigger (e.g. 100x120). In those last 20 pixels I have an arrow that is supposed to point to a person's location on a map. Then I think I could do something like this:

Drawable[] layers = new Drawable[2];
layers[0] = res.getDrawable(R.drawable.background_img);
layers[1] = res.getDrawable(R.drawable.icon);
LayerDrawable layerDrawable = new LayerDrawable(layers);

But this simply overlays one image onto another ignoring their bounds.

Thanks in advance, Vaidas

-- UPDATE: Finally solved the problem. Works like a charm :)

private Drawable createPersonDrawable(Bitmap personImage)
{
    Bitmap resultingBitmap = Bitmap.createBitmap(drawableWidth,
            drawableHeight, Bitmap.Config.ARGB_8888);
    Canvas comboCanvas = new Canvas(resultingBitmap);

    comboCanvas.drawBitmap(personImage, 0, 0, null);

    // Get the bottom part of the image from resources
    Bitmap bottomPart = BitmapFactory.decodeResource(getResources(),
            R.drawable.person_map_icon_bottom);

    comboCanvas.drawBitmap(bottomPart, 0, drawablePersonImageHeight, null);
    comboCanvas.save();

    return new BitmapDrawable(resultingBitmap);
}

I found the description here: http://www.jondev.net/articles/Combining_2_Images_in_Android_using_Canvas


Solution

  • I don't have the exact commands here but you should do:

    1. Create a Bitmap with the total size you want.
    2. Create a Canvas passing the created Bitmap
    3. Draw the two images on the Canvas.
    4. Add the Bitmap to the view you are using.