2

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

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

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

我的叠加层上有一个 ArrayList(扩展 BalloonItemizedOverlay)。叠加层的 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);
}

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

这里有一些图片,当它决定选择一个更大的标记时,一切正常:

金刚狼更长,所以看起来还不错

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

野兽有点矮,溢出来了

4

1 回答 1

1

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

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

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

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

于 2012-11-02T19:18:51.797 回答