首页 > 解决方案 > 字符串 SVG 到 Google 地图标记

问题描述

我有 svg,关于这个

<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="20" fill="#FFFFFF" stroke="#000000" stroke-width="1"/>
    <text fill="#FF0000" font-size="12" x="8" y="24">{text}</text>
</svg>

我想把它作为谷歌地图标记的图标。我想更改每个标记的文本。我怎样才能做到这一点?

UPD

标记桅杆的图标是 BitmapDescriptor 对象。要创建它,我有 5 个选项:

BitmapDescriptorFactory.fromBitmap(Bitmap bitmap);
BitmapDescriptorFactory.fromResource(int resourceId);
BitmapDescriptorFactory.fromAsset(String s);
BitmapDescriptorFactory.fromPath(String s);
BitmapDescriptorFactory.fromFile(String s);

我想我可以使用 fromPath 但我有例外:

Failed to decode image. The provided image must be a Bitmap.

我需要将我的 svg 字符串转换为 BitmapDescriptorFactory 接受的格式

标签: androidgoogle-mapssvg

解决方案


您可以通过 3 个步骤来完成:

1)String带有标记文本的格式:

public String formatText(String text) {
    return String.format("<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" xmlns=\"http://www.w3.org/2000/svg\">\n" +
            "    <circle cx=\"20\" cy=\"20\" r=\"20\" fill=\"#FFFFFF\" stroke=\"#000000\" stroke-width=\"1\"/>\n" +
            "    <text fill=\"#FF0000\" font-size=\"12\" x=\"8\" y=\"24\">%s</text>\n" +
            "</svg>", text);
}

2) 从目标 SVG 创建位图String,例如,通过AndroidSVGSVG.renderToPicture()的方法:

public Bitmap renderToBitmap(String svgString, int requiredWidth) {
    Bitmap bitmap = null;
    SVG  svg = null;
    try {
        svg = SVG.getFromString(svgString);

        if (requiredWidth < 1) requiredWidth = (int)svg.getDocumentWidth();

        float scaleFactor = (float)requiredWidth / (float)svg.getDocumentWidth();
        int adjustedHeight = (int)(scaleFactor * svg.getDocumentHeight());

        bitmap = Bitmap.createBitmap(requiredWidth, adjustedHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPicture(svg.renderToPicture(), new Rect(0, 0, requiredWidth, adjustedHeight));
    } catch (SVGParseException e) {
        e.printStackTrace();
    }

    return bitmap;
}

3)将其添加为标记图标:

mGoogleMap.addMarker(new MarkerOptions()
        .position(<POSITION>)
        .icon(BitmapDescriptorFactory.fromBitmap(renderToBitmap(formatText("text"), <ICON_WIDTH_IN_PIXELS>)))
        .anchor(0.5f, 0.5f));

推荐阅读