前言
百度地图的安卓 sdk 提供了点位标记功能
https://lbsyun.baidu.com/faq/api?title=androidsdk/guide/render-map/point
var marker: MarkerOptions? = MarkerOptions() marker?.anchor(0.5f, 0.5f) var lng = LatLng( map["x_point"].toString().toDouble(), map["y_point"].toString().toDouble(), ) LatLngs?.add(lng); marker?.position( lng ) marker?.visible(true) marker?.draggable(false) // 设置点位图标 marker?.icon(BitmapDescriptorFactory.fromResource(R.mipmap.people_green))
但是如果想要在图标上加文字应该怎么办呢
方案
将要写入的文字和图标生成到同一个 Bitmap 中返回
/** * 创建文字图片并转换为Bitmap */ fun createTextImage(text: String, backgroundResId: Int, context: Context): Bitmap { val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG) textPaint.color = Color.YELLOW textPaint.textSize = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 12f, context.resources.displayMetrics ) textPaint.setShadowLayer(3f, 0f, 0f, Color.BLACK) val staticLayout = StaticLayout( text, textPaint, 200, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false ) // 加载背景图片 val backgroundBitmap = BitmapFactory.decodeResource(context.resources, backgroundResId) // 创建一个足够大的位图来容纳背景图片和文本,文字单行大概 60 val bitmap = Bitmap.createBitmap( backgroundBitmap.width , backgroundBitmap.height + 60, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) // 绘制背景图片 canvas.drawBitmap(backgroundBitmap, 0f, 0f, null) // 计算文本绘制的位置,设置水平居中,垂直偏移 val x = (backgroundBitmap.width - staticLayout.width) / 2f val y = backgroundBitmap.height / 1f // 绘制文本 canvas.translate(x, y) canvas.drawColor(Color.TRANSPARENT) staticLayout.draw(canvas) return bitmap }
使用
······省略代码 // 图标增加覆盖物 val bitmapText = createTextImage(map["show_mark"].toString(),R.mipmap.people_yellow,this) val bitmap = BitmapDescriptorFactory.fromBitmap(bitmapText) marker?.icon(bitmap)