Android Drawable Marker with Bitmap Text Overlay t

2019-09-02 15:07发布

问题:

I am creating a Marker with text but the text is showing only 3 characters and very small and it is right of the bit map image. I want the text to go across the middle of the icon and it big font. I manually increased setFontsize to larger size did not work and also drawText width and height still did not work.

private Drawable createMarkerIcon(Drawable backgroundImage, String text,
        int width, int height) {

Bitmap canvasBitmap = Bitmap.createBitmap(width, height, 
                  Bitmap.Config.ARGB_8888);  //width, height,
// Create a canvas, that will draw on to canvasBitmap.
Canvas imageCanvas = new Canvas(canvasBitmap);

// Set up the paint for use with our Canvas
Paint imagePaint = new Paint();
imagePaint.setTextAlign(Align.CENTER);
imagePaint.setTextSize(26f); // 8f

// Draw the image to our canvas
backgroundImage.draw(imageCanvas);

// Draw the text on top of our image
imageCanvas.drawText(text, width /1, height / 1, imagePaint); //2 , 2

// Combine background and text to a LayerDrawable
LayerDrawable layerDrawable = new LayerDrawable(
new Drawable[]{backgroundImage, new BitmapDrawable(canvasBitmap)});
return  layerDrawable;
}

I call this function:

d=createMarkerIcon(getResources().getDrawable(R.drawable.pointer_bubble_selected), markerTxt, 100, 100);  //marker_green=23x37 29, 50

回答1:

Here is the solution for the text overlay bound problem. Replace one line with all this lines:

// draw text to the Canvas center
  Rect bounds = new Rect();
  int x = (canvasBitmap.getWidth() - bounds.width())/2;
  int y = (canvasBitmap.getHeight() + bounds.height())/2;



// Draw the text on top of our image
//imageCanvas.drawText(text, width /4, height / 4, imagePaint); //OLD
imageCanvas.drawText(text, x , y, imagePaint); //NEW