The answer by Blue_Alien does not work with vector drawables in Kotlin. The reason is due to BitmapFactory
: it returns an error.
If you are programming in kotlin, there is a significantly simpler solution than using BitmapFactory
.
Firstly, get the drawable:
val drawable = ContextCompat.getDrawable(context, R.drawable.order_pin)!!
Then simply use the toBitmap()
function:
val bitmap = drawable.toBitmap()
And then the rest of the solution is effectively the same.
Final code:
val drawable = ContextCompat.getDrawable(context, R.drawable.order_pin)!!
val bitmap = drawable.toBitmap()
val paint = Paint();
paint.style = Style.FILL
paint.color = Color.BLACK
paint.textSize = 20
val canvas = Canvas(bitmap)
// Note, this code places the text in the center of the Bitmap (both vertically and horizontally)
// https://stackoverflow.com/a/11121873
canvas.drawText(text, bm.width / 2f,
bm.height / 2f - (paint.descent() + paint.ascent() / 2), paint)
val iconWithText = BitmapDrawable(context.resources, bitmap)
// Marker has to be initialised somewhere in your code
marker.icon = iconWithText
Of course, this code if for one time use. If you want to move it to a function, the parameter could either be the drawable or drawableID, and it would return the icon
:
return BitmapDrawable(context.resources, bitmap)