Kotlin/Android 谷歌地图Lite模式下自定义Marker旋转失效问题问询
问题根因
- 谷歌地图Lite模式本身不支持
MarkerOptions.rotation属性,该属性仅在完全交互模式下生效 IconGenerator.setRotation()方法的作用是设置内部文本/内容的旋转角度,而非对最终生成的整张图标Bitmap做全局旋转,因此无法实现箭头类图标的旋转效果
可行解决方案
核心思路是手动旋转目标图标Bitmap后再传入MarkerOptions,完全绕过Lite模式不支持的属性限制:
第一步:实现Bitmap旋转工具方法
fun rotateBitmap(source: Bitmap, angle: Float): Bitmap { val matrix = Matrix() matrix.postRotate(angle) return Bitmap.createBitmap( source, 0, 0, source.width, source.height, matrix, true ) }
第二步:改造Marker添加逻辑
// 1. 先生成原始未旋转的图标Bitmap val originalIcon = IconGenerator(context).run { setBackground(resources.getDrawable(R.drawable.ic_arrow_head, null)) makeIcon() } // 2. 手动旋转Bitmap到目标角度 val rotatedIcon = rotateBitmap(originalIcon, 33f) // 3. 将旋转后的Bitmap设置给Marker val marker = map.addMarker( MarkerOptions() .position(arrowPointPosition) .icon(BitmapDescriptorFactory.fromBitmap(rotatedIcon)) .anchor(0.5F, 0.5F) )
注意事项
- 如果需要动态更新Marker的旋转角度,只能调用
marker.setIcon()重新传入新的旋转后Bitmap,Lite模式下不支持直接修改rotation属性更新 - 及时回收不再使用的Bitmap,避免内存泄漏
- 如果是直接用Drawable转Bitmap,也可以在转成Bitmap之后再调用上述旋转方法,效果一致
内容的提问来源于stack exchange,提问作者user11190851
相关产品推荐
相关产品推荐

