Archive for January, 2012

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

,

3 Comments