Combine image and text to drawable

后端 未结 1 988
既然无缘
既然无缘 2020-12-04 12:37

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

相关标签:
1条回答
  • 2020-12-04 13:28

    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.

    0 讨论(0)
提交回复
热议问题