安卓Mapbox:如何更改标记图标的颜色

5

我在我的Android应用中使用Mapbox,并为我的标记使用自定义(黑色)图标。如果一个标记是黑色的,是否有可能将其图标颜色更改为其他颜色?

如果可以使用默认图标,则也可以使用默认图标。

4个回答

12

Mapbox Android SDK 使用PNG文件作为标记图标。您可以使用任何PNG文件作为图标,换句话说,标记可以是任何颜色。这里有一个示例,其中使用自定义图标的标记。这是示例,下面是主要代码:

            // Create an Icon object for the marker to use
            IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
            Drawable iconDrawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.purple_marker);
            Icon icon = iconFactory.fromDrawable(iconDrawable);

            // Add the custom icon marker to the map
            mapboxMap.addMarker(new MarkerOptions()
                    .position(new LatLng(-33.8500000, 18.4158234))
                    .title("Cape Town Harbour")
                    .snippet("One of the busiest ports in South Africa")
                    .icon(icon));

我用与默认图标相同的样式制作了一些标记:

将它们放在你的项目的drawable-xxhdpi文件夹中。这些图片可从Google Play商店下载的Mapbox Android Demo app中获取。


谢谢!虽然我不认为这个方法可以让我以编程的方式改变颜色,但我认为这个链接会有所帮助:https://dev59.com/YWgu5IYBdhLWcg3wYF-3 - Anna Evtushenko
在我的情况下,我正在处理位图,因为针的图形不是从应用程序内部而是从服务器获取的。我必须从服务器下载此标记图标。每次我为某些场合设置多个setIcon时,标记会从地图上移除自己。我想知道为什么?我猜测它可能是OOM。 - Neon Warge
1
很不幸,由于fromDrawable已不再受支持,因此这将不再起作用。但是,使用png(R.drawable.<name>)的fromResource将可以正常工作。 - officialgupta

3

我使用这个

 map.addMarker(new MarkerOptions()
            .position(new LatLng(lat,lng))
            .icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_marker))
    );

2
您可以通过编程方式更改图标的颜色。
Drawable iconDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.your_marker, null);
iconDrawable = DrawableCompat.wrap(iconDrawable);
//Changing color to white
DrawableCompat.setTint(iconDrawable, Color.WHITE);
//Use this icon in addMarker(new MarkerOptions()...
Icon icon = iconFactory.fromDrawable(iconDrawable);

0

对于SDK版本5及以上,其他解决方案不再适用,因为方法fromDrawable()不再可用。

使用以下方法从可绘制资源创建一个带色图标:

public static Icon drawableToIcon(@NonNull Context context, @DrawableRes int id, @ColorInt int colorRes) {
    Drawable vectorDrawable = ResourcesCompat.getDrawable(context.getResources(), id, context.getTheme());
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
    vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    DrawableCompat.setTint(vectorDrawable, colorRes);
    vectorDrawable.draw(canvas);
    return IconFactory.getInstance(context).fromBitmap(bitmap);
}

代码片段取自GitHub问题,该问题还解释了为什么fromDrawable()不再可用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接