Android MapView自定义标记大小都相同

时间:2012-11-02 14:58:22

标签: android android-mapview google-maps-markers itemizedoverlay

我正在编写一个应用程序,它将显示带有一堆标记的地图。我希望标记是动态的(在它们上显示动态内容)。因为标记内容是动态的,所以每个标记的大小是不同的。

我在文档中发现这一点,说“不同状态可以返回不同的标记。不同的标记可以有不同的边界。”在这里:https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/OverlayItem#getMarker(int)

我认为这意味着同一叠加层上的多个标记可以是不同的大小。这是对的吗?

我的叠加层上有一个ArrayList(扩展了BalloonItemizedOverlay)。 overlay的createItem()方法如下所示:

@Override
protected OverlayItem createItem(final int index)
{
    final Person person = people.get(index);
    final GeoPoint gp = new GeoPoint(person.getLat(), person.getLng());

    final OverlayItem oi = new OverlayItem(gp, person.getName(), person.getName());
    oi.setMarker(new PersonDrawable(defaultMarker, person));

    return oi;
}

然后在我的PersonDrawable中有一个drawable,它有一个9补丁作为背景图像,然后在它上面绘制文字:

public PersonDrawable(final Drawable iBackground, final Person person)
{
    background = iBackground;
    text = person.getName();
    padding = new Rect();

    if (background instanceof NinePatchDrawable)
    {
        // This is getting hit, and just sets the value of the padding
        final NinePatchDrawable ninePatch = (NinePatchDrawable) background;
        ninePatch.getPadding(padding);
    }

    // set the bounds of the marker
    bounds = background.getBounds();

    paint = new Paint();
    paint.setColor(Color.rgb(255, 255, 255));
    paint.setFakeBoldText(true);
    paint.setTextSize(30);

    // find the bounds of the text
    final Rect textBounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), textBounds);

    // set the left and right bounds to that of the text plus the padding (then center it)
    bounds.left = 0 - (textBounds.width() / 2) - padding.left;
    bounds.right = 0 + (textBounds.width() / 2) + padding.right;

    // set the bounds of the drawable
    setBounds(bounds);
}

@Override
public void draw(final Canvas canvas)
{
    // when it's time to draw, draw the background
    background.draw(canvas);
    // then draw the text within the padding
    canvas.drawText(text, bounds.left + padding.left, bounds.bottom - padding.bottom, paint);
}

每个标记都有一个不同的边界集,即使它在覆盖图上绘制后它的边界也是不同的。 MapView(或Overlay)不会重复使用createItem()中的对象。但是Overlay似乎总是选择一个标记,并假设它是所有标记的大小。这只是行为吗?我能做些什么来让它尊重每个标记的界限?

以下是一些图片,当它决定选择一个更大的标记时,结果确定不错:

Wolverine is longer so things look alright

然而,当它选择使用较小的标记作为大小时:

Beast is a little shorter and overflow

1 个答案:

答案 0 :(得分:1)

问题是当从资源加载Drawable时,它被视为可共享资源。来自Drawable文档:

  

默认情况下,从同一资源加载的所有drawables实例共享一个公共状态;如果修改一个实例的状态,则所有其他实例将收到相同的修改。

OverlayItem中,假设Drawable始终具有相同的大小。您看到的效果是Drawable的最后一次修改覆盖了之前的所有修改,因此Drawable的所有显示都显示完全相同。

解决方案是防止共享Drawable的修改。您可以使用mutate()方法结合资源中的多个Drawable加载来执行此操作。您应该与上面概述的PersonDrawable构造函数一起执行此操作。

相关问题