android - 为 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 中一样添加色调?目标是为多种目的重复使用相同的图像资源——只是颜色会有所不同。
解决方案
我从这篇文章中找到了很多灵感并得到了这个解决方案:
我创建了这个方法:
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)
}
变暗混合模式将对白色区域重新着色,同时将黑色区域排除在外。
推荐阅读
- excel - 从 excel 宏更新数据源 (SAP) 时,有没有办法抑制询问查询参数的提示?
- powershell - 如何转义未知字符串并将其传递给本机命令
- ios - 是否可以从初始 tableview 控制器转换到 UISplitViewController?
- sql - 在sql中使用OUTPUT返回插入的行JAVASCRIPT/NODEJS/PG
- java - Spring boot - 使用配置文件时未读取默认属性文件
- sql - 在将我的 SQL 表列中的某些值转换为十进制时需要帮助
- oracle - 如何从列中提取时间并从 Oracle 中的自定义时间中减去
- javascript - 如何使用 Express js 保护简单的 GET 请求
- java - 我试图计算一些字符串的 hashCode 但失败了,我做错了什么?
- javascript - 在包括 $get (jQuery) 的 for 循环中填充一个数组 - i 没有增加