android - 字符串 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 接受的格式
解决方案
您可以通过 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
,例如,通过AndroidSVG库SVG.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));
推荐阅读
- c++ - Fusion有尾部功能吗?
- javascript - Console.table 显示不带引号的字符串
- reactjs - 如何使用 Yup 验证一个字段与另一个字段?
- angular - 如何在 Angular 中将值从 .ts/html 传递到 css/scss?
- join - 将两个分区表合并为一张表,但合并为两个不同的分区
- wcf - System.Net.Sockets.SocketException:现有连接被远程主机强行关闭
- flutter - 为 CircleAvatar wiget (Flutter) 隐藏溢出
- numpy - 根据条件重塑神经网络输入
- java - 处理时间加倍的功能问题
- graphql - GraphQL 错误 FieldsConflict:字段具有不同的列表形状