Android – Combine image and text to drawable

androidandroid-mapviewdrawable

I want to create a drawable, which consists of a map pin(bubble) and some text. The bubble should be in the background and the text in the foreground.

This drawable should be passed in super(drawable) of the class BalloonItemizedOverlay which extends ItemizedOverlay<Item>.

In other words, I want to show text in the bubble that appears in the map.

I am using the Hello Mapview tutorial

Best Solution

This method takes a drawable from your resources, draws some text on top of it and returns the new drawable. All you need to do is give it the resource id of your bubble, and the text you want on top. Then you can pass the returned drawable wherever you want it.

public BitmapDrawable writeOnDrawable(int drawableId, String text){

        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL);  
        paint.setColor(Color.BLACK); 
        paint.setTextSize(20); 

        Canvas canvas = new Canvas(bm);
        canvas.drawText(text, 0, bm.getHeight()/2, paint);

        return new BitmapDrawable(bm);
    }

To preserve density you need this constructor

BitmapDrawable (Resources res, Bitmap bitmap)

So, keeping your context, last return should be something like

return new BitmapDrawable(context.getResources(), bm);

This prevent an undesired resized drawable.