Android: draw a number of bitmaps or drawables into a single drawable

In some cases, you might need to render a numer of bitmaps or drawables into a single drawable. For instance, swapping LayerDrawables of different sizes displayed on top of MapView, might render not as it is supposed to. Code snippet below shows how to render LayerDrawable into a single BitmapDrawable. It is a simplified piece of code and contains “magic numbers”, but anyway, this should show the idea:


public Drawable getPersonMapItemDrawable(Drawable drawable1, Drawable drawable2){

  Drawable[] layers = new Drawable[2];
  layers[0] = drawable1;
  layers[1] = drawable2;

  int resourceBitmapHeight = 136, resourceBitmapWidth = 153;

  float widthInInches = 0.9f;

  int widthInPixels = (int)(widthInInches * context.getResources().getDisplayMetrics().densityDpi);
  int heightInPixels = (int)(widthInPixels * resourceBitmapHeight / resourceBitmapWidth);

  int insetLeft = 10, insetTop = 10, insetRight = 10, insetBottom = 10;

  LayerDrawable layerDrawable = new LayerDrawable(layers);
  layerDrawable.setLayerInset(1, insetLeft, insetTop, insetRight, insetBottom);		
  
  Bitmap bitmap = Bitmap.createBitmap(widthInPixels, heightInPixels, Bitmap.Config.ARGB_8888);

  Canvas canvas = new Canvas(bitmap);
  layerDrawable.setBounds(0, 0, widthInPixels, heightInPixels);
  layerDrawable.draw(canvas);
		
  BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
  bitmapDrawable.setBounds(0, 0, widthInPixels, heightInPixels);
		
  return bitmapDrawable;
}
Advertisements

,

  1. #1 by julika on February 8, 2012 - 4:48 am

    thanks a lot….

  2. #2 by Lanny on November 23, 2013 - 1:47 am

    what does setLayerInset do? not sure what these int insetLeft = 10, insetTop = 10, insetRight = 10, insetBottom = 10; mean, is it the (left, top), (right, bottom) of the tow corner of the rectangle?

    • #3 by jacekdalkowski on November 25, 2013 - 2:40 pm

      As you said, these inset values are “margin distances”. I set these values to constants (magic numbers 😦 ) in order to simplify the code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: