我在我的Android应用中使用Mapbox,并为我的标记使用自定义(黑色)图标。如果一个标记是黑色的,是否有可能将其图标颜色更改为其他颜色?
如果可以使用默认图标,则也可以使用默认图标。
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中获取。
我使用这个
map.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_marker))
);
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);
对于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);
}
fromDrawable()
不再可用。