android - adding a String over a Drawable image?

这一生的挚爱 提交于 2019-11-30 05:43:37

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;
}
Drawable image = getResources().getDrawable(tile_types[tileType]);
// Store our image size as a constant
final int IMAGE_WIDTH = image.getIntrinsicWidth();
final int IMAGE_HEIGHT = image.getIntrinsicHeight();

// You can also use Config.ARGB_4444 to conserve memory or ARGB_565 if 
// you don't have any transparency.
Bitmap canvasBitmap = Bitmap.createBitmap(IMAGE_WIDTH, 
                                          IMAGE_HEIGHT, 
                                          Bitmap.Config.ARGB_8888);
// Create a canvas, that will draw on to canvasBitmap. canvasBitmap is
// currently blank.
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
image.draw(imageCanvas);
// Draw the text on top of our image
imageCanvas.drawText("Sample Text", 
                         IMAGE_WIDTH / 2, 
                         IMAGE_HEIGHT / 2, 
                         imagePaint);
// This is the final image that you can use 
BitmapDrawable finalImage = new BitmapDrawable(canvasBitmap);

If your resulted text looks "angular" due to resizing, it's better to use TextPaint instead of plain Paint with these parameters:

TextPaint textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG | TextPaint.LINEAR_TEXT_FLAG);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!