【问题标题】:How to use custom icon of Google Maps Marker in Compose?如何在 Compose 中使用 Google Maps Marker 的自定义图标?
【发布时间】:2022-01-05 18:43:27
【问题描述】:

问题 如果我使用以下帮助程序/扩展程序,我将收到异常 IBitmapDescriptorFactory is not initialized

我检查了 Stackoverflow,其中一些建议创建工厂的本地属性并分配它,但这也不起作用。

Android Studio 向我显示右侧的图标,因此我认为资产已正确添加。

来源

fun Webcam.toMarkerOptions(): MarkerOptions {

    return MarkerOptions()
        .title(name)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_webcam))
        .position(coordinate.toLngLat())
}

同样崩溃的源 2

fun MarkerOptions.icon(context: Context, @DrawableRes vectorDrawable: Int): MarkerOptions {
    this.icon(ContextCompat.getDrawable(context, vectorDrawable)?.run {
        setBounds(0, 0, intrinsicWidth, intrinsicHeight)
        val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
        draw(Canvas(bitmap))
        BitmapDescriptorFactory.fromBitmap(bitmap)
    })
    return this
}

【问题讨论】:

    标签: android kotlin google-maps-markers


    【解决方案1】:

    我为此创建了 MapMarker 可组合方法,它采用 resourceId:

    @Composable
    fun MapMarker(
        context: Context,
        position: LatLng,
        title: String,
        snippet: String,
        @DrawableRes iconResourceId: Int
    ) {
        val icon = bitmapDescriptor(
            context, iconResourceId
        )
        Marker(
            position = position,
            title = title,
            snippet = snippet,
            icon = icon,
        )
    }
    

    在哪里位图描述符:

    fun bitmapDescriptor(
        context: Context,
        vectorResId: Int
    ): BitmapDescriptor? {
    
        // retrieve the actual drawable
        val drawable = ContextCompat.getDrawable(context, vectorResId) ?: return null
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        val bm = Bitmap.createBitmap(
            drawable.intrinsicWidth,
            drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888
        )
    
        // draw it onto the bitmap
        val canvas = android.graphics.Canvas(bm)
        drawable.draw(canvas)
        return BitmapDescriptorFactory.fromBitmap(bm)
    }
    

    更多详情:https://erselankhan.medium.com/jetpack-compose-custom-google-map-marker-erselan-khan-e6e04178a30b

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2020-07-31
      相关资源
      最近更新 更多