Function to convert a vector asset to bitmap

- Posted in Markers by

Function to convert a vector asset to bitmap

1️⃣ First, add the giveMeBitmapDescriptor function:

private fun giveMeBitmapDescriptor(
    context: Context,
    iconPrm: Int
): BitmapDescriptor? {
    val background = ContextCompat.getDrawable(context, iconPrm)
    background!!.setBounds(0, 0, background.intrinsicWidth, background.intrinsicHeight)
    val bitmap = Bitmap.createBitmap(
        background.intrinsicWidth,
        background.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    background.draw(canvas)
    val r = Rect()
    canvas.getClipBounds(r)
    val cHeight: Int = r.height()
    val cWidth: Int = r.width()
    val paint = Paint()
    paint.setTextAlign(Paint.Align.LEFT)
    paint.getTextBounds("text 1234567890", 0, "text 0002".length, r)
    val x: Float = cWidth / 2f - r.width() / 2f - r.left
    val y: Float = cHeight / 2f + r.height() / 2f - r.bottom
    canvas.drawText("sample text", x, y, paint)
    return BitmapDescriptorFactory.fromBitmap(bitmap)
}



2️⃣ Then set marker options as usual, but use the giveMeBitmapDescriptor to declare the icon:

    val markerOptionSVG = MarkerOptions()
        .position(LatLng(25.16828, 121.44430))
        .title("test")
        .snippet("sLcl2")
        .icon(giveMeBitmapDescriptor(this,R.drawable.SampleVectorImage))

    mMap.addMarker(markerOptionSVG)


Source:
[1] https://stackoverflow.com/questions/17837510/map-markers-with-text-in-google-maps-android-api-v2