android - adding a String over a Drawable image?

前端 未结 3 1569
猫巷女王i
猫巷女王i 2020-12-29 16:08

I\'m trying to add a String to a Drawable image. I\'m currently not using a Panel to draw and I\'d like to keep it that way. Any idea

3条回答
  •  温柔的废话
    2020-12-29 16:26

    Sam's answer was my starting point, but the image didn't show up, only the text (I use it on a Google Map). Finally I got it working with a LayerDrawable. Here is my solution:

    private Drawable createMarkerIcon(Drawable backgroundImage, String text,
                                      int width, int height) {
    
      Bitmap canvasBitmap = Bitmap.createBitmap(width, height, 
                                                Bitmap.Config.ARGB_8888);
      // 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(16f);
    
      // Draw the image to our canvas
      backgroundImage.draw(imageCanvas);
    
      // Draw the text on top of our image
      imageCanvas.drawText(text, width / 2, height / 2, imagePaint);
    
      // Combine background and text to a LayerDrawable
      LayerDrawable layerDrawable = new LayerDrawable(
                 new Drawable[]{backgroundImage, new BitmapDrawable(canvasBitmap)});
      return layerDrawable;
    }
    

提交回复
热议问题