首页 > 解决方案 > 为 Google Maps API 中使用的自定义图标着色

问题描述

我在 Android 应用程序中有一个谷歌地图视图,并创建了一个自定义标记图标(来自 svg),如下所示:

用途

mMap.addMarker {
    position(LatLng(mLastLocation.latitude, mLastLocation.longitude))
    title("Path marker")
    icon(bitmapDescriptorFromVector(this@DrivingActivity, R.drawable.ic_marker))
    anchor(0.5F,0.5F)
    flat(true)
}

方法

private fun bitmapDescriptorFromVector(context: Context, vectorResId: Int): BitmapDescriptor? {
    return ContextCompat.getDrawable(context, vectorResId)?.run {
        setBounds(0, 0, 44, 36)
        val bitmap = Bitmap.createBitmap(44, 36, Bitmap.Config.ARGB_8888)
        draw(Canvas(bitmap))
        BitmapDescriptorFactory.fromBitmap(bitmap)
    }
}

如何像在 ImageViews 中一样添加色调?目标是为多种目的重复使用相同的图像资源——只是颜色会有所不同。

标签: androidkotlingoogle-maps-markers

解决方案


我从这篇文章中找到了很多灵感并得到了这个解决方案:

我创建了这个方法:

private fun vectorToBitmap(@DrawableRes id: Int, @ColorInt color: Int, width: Int, height: Int): BitmapDescriptor? {
    val vectorDrawable: Drawable? = ResourcesCompat.getDrawable(resources, id, null)

    if(vectorDrawable != null) {
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

        val canvas = Canvas(bitmap)
        vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
        DrawableCompat.setTint(vectorDrawable, color)
        vectorDrawable.setTintBlendMode(BlendMode.DARKEN)
        vectorDrawable.draw(canvas)

        return BitmapDescriptorFactory.fromBitmap(bitmap)
    }

    return null
}

它是这样使用的:

mMap.addMarker {
    position(LatLng(mLastLocation.latitude, mLastLocation.longitude))
    title("Path marker")
    icon(vectorToBitmap(R.drawable.ic_bale, Color.parseColor("#FFCA22"), 44, 33))
    //icon(bitmapDescriptorFromVector(this@DrivingActivity, R.drawable.ic_bale))
    anchor(0.5F,0.5F)
    flat(true)
}

变暗混合模式将对白色区域重新着色,同时将黑色区域排除在外。


推荐阅读