Android: How to overlay a bitmap and draw over a bitmap?

I can’t believe no one has answered this yet! A rare occurrence on SO!


The question doesn’t quite make sense to me. But I’ll give it a stab.
If you’re asking about direct drawing to a canvas (polygons, shading, text etc…) vs. loading a bitmap and blitting it onto the canvas that would depend on the complexity of your drawing.
As the drawing gets more complex the CPU time required will increase accordingly.
However, blitting a bitmap onto a canvas will always be a constant time which is proportional to the size of the bitmap.


Without knowing what “something” is how can I show you how to do it?
You should be able to figure out #2 from the answer for #3.



  • bmp1 is larger than bmp2.
  • You want them both overlaid from the top left corner.

        private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);
            canvas.drawBitmap(bmp2, new Matrix(), null);
            return bmOverlay;

You can do something like this:

public void putOverlay(Bitmap bitmap, Bitmap overlay) {
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(overlay, 0, 0, paint);

The idea is very simple: Once you associate a bitmap with a canvas, you can call any of the canvas’ methods to draw over the bitmap.

This will work for bitmaps that have transparency. A bitmap will have transparency, if it has an alpha channel. Look at Bitmap.Config. You’d probably want to use ARGB_8888.

Important: Look at this Android sample for the different ways you can perform drawing. It will help you a lot.

Performance wise (memory-wise, to be exact), Bitmaps are the best objects to use, since they simply wrap a native bitmap. An ImageView is a subclass of View, and a BitmapDrawable holds a Bitmap inside, but it holds many other things as well. But this is an over-simplification. You can suggest a performance-specific scenario for a precise answer.

public static Bitmap overlayBitmapToCenter(Bitmap bitmap1, Bitmap bitmap2) {
    int bitmap1Width = bitmap1.getWidth();
    int bitmap1Height = bitmap1.getHeight();
    int bitmap2Width = bitmap2.getWidth();
    int bitmap2Height = bitmap2.getHeight();

    float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
    float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);

    Bitmap overlayBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
    Canvas canvas = new Canvas(overlayBitmap);
    canvas.drawBitmap(bitmap1, new Matrix(), null);
    canvas.drawBitmap(bitmap2, marginLeft, marginTop, null);
    return overlayBitmap;