Я пытаюсь настроить в маркер карты, так что он может быть отображен с 3-мя основные особенностей:Google Map Marker с пользовательским фоном и текстом
- 9patch Drawable в качестве фона
- Пользовательского текст
- Факультативного рисуем слева от текста (некоторые маркеры есть, то нет)
Я использовал IconGenerator от андроида google map utils library, но так или иначе затронута вся область действия кликаемой метки. Очень большая область вокруг маркера является интерактивной и активирует маркер. Он также имеет проблемы с атрибутами содержимого и гравитацией.
Я добавил пользовательский хак на карту, чтобы вывести на передний план маркеры, не открывая информационное окно (я установил информационное окно без содержимого для отображения, и я вызвал showInfoWindow в прослушивателе событий щелчка маркера).
Как я могу вручную создать значок маркера и избежать проблемы с большой зоной вокруг нее?
Я также попытался реализации описанной here, в основном метод drawTextToBitmap():
private Bitmap drawTextToBitmap(@DrawableRes int backgroundRes, String text) {
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, backgroundRes);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// SET FONT COLOR (e.g. WHITE -> rgb(255,255,255))
paint.setColor(Color.rgb(255, 255, 255));
// SET FONT SIZE (e.g. 15)
paint.setTextSize((int) (15 * scale));
// SET SHADOW WIDTH, POSITION AND COLOR (e.g. BLACK)
paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x = (bitmap.getWidth() - bounds.width())/2;
int y = (bitmap.getHeight() + bounds.height())/2;
canvas.drawText(text, x, y, paint);
return bitmap;
}
Но это не работает, как ожидалось, потому что мой текст больше, чем фон, и я также не» t знать, как добавить ресурс слева от текста.
Это реализация для IconGenerator Я использую:
private BitmapDescriptor getBitmapDescriptorForProduct(@NonNull final MyCustomObject product, boolean isActive) {
if (product.shouldDisplayWithLabel) {
// We use an custom layout for displaying markers on the map
@SuppressLint("InflateParams") View view =
LayoutInflater.from(getActivity()).inflate(R.layout.my_custom_label, null);
// Get the text view which will display the text
TextView label = (TextView) view.findViewById(R.id.text);
// Set the left drawable if needed
label.setCompoundDrawablesWithIntrinsicBounds(product.shouldDisplayWithDrawable ? R.drawable.my_custom_drawable : 0, 0,
0, 0);
// Set the text for the label
label.setText(product.label);
label.setBackgroundResource(R.drawable.my_custom_background);
// Set the layout for the icon
mIconGenerator.setContentView(view); // set the custom layout
// We don't want the default background
mIconGenerator.setBackground(null);
// Disable the content padding as we handle it in the view and in the 9patch resources
mIconGenerator.setContentPadding(0, 0, 0, 0);
// Make the icon and create the BitmapDescriptor necessary for the marker creation
Bitmap icon = mIconGenerator.makeIcon();
return BitmapDescriptorFactory.fromBitmap(icon);
} else {
// Lazy initialization for the normal markers
if (null == simpleMarkerIcon) {
simpleMarkerIcon = BitmapDescriptorFactory.fromResource(R.drawable.my_simple_marker);
}
// Reuse the bitmap for the simple markers that will be displayed on the map.
return simpleMarkerIcon;
}
}
LE: @Harpreet, это как значки маркеров будут выглядеть, используя свое решение:
Как вы можете видеть, свойства представления отображаются неправильно в растровом изображении.
Кажется, что этот метод очень интенсивен для памяти, и я получаю исключение OOM в 99% случаев. –
Я также добавил SS с результатом растрового изображения, используя ваш метод. –
Вам также нужно использовать Google Clustering, если у вас есть многочисленные маркеры, которые будут отображаться на карте одновременно. – Harpreet