[英]Mapbox for Android: Changing color of a marker's icon
我在我的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
文件夾中。 這些是從您可以從Play商店獲得的Mapbox Android Demo應用程序中提取的
您可以通過編程方式更改圖標的顏色
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);
我用這個
map.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_marker))
);
對於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()
不再可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.