小编典典

如何在Flutter中更改Google Maps标记的图标大小?

flutter

google_maps_flutter在我的flutter应用程序中使用了Google地图,我有
自定义标记图标,但我将其加载,
BitmapDescriptor.fromAsset("images/car.png")但是我在地图上的图标尺寸
太大,我想使其变小,但我找不到任何选择,没有任何选择更改自定义标记图标。这是我的颤动代码:

mapController.addMarker(
        MarkerOptions(
          icon: BitmapDescriptor.fromAsset("images/car.png"),

          position: LatLng(
            deviceLocations[i]['latitude'],
            deviceLocations[i]['longitude'],
          ),
        ),
      );

如您在图片中看到的,我的自定义图标尺寸太大


阅读 926

收藏
2020-08-13

共1个答案

小编典典

TL; DR:只要能够将任何图像编码为原始字节(例如)
Uint8List,就可以将其用作标记。

截至目前,您可以使用Uint8List数据在Google
地图中创建标记。也就是说 ,只要您保持正确的编码格式(在此 特定情况下为),就可以使用原始数据将所需的内容绘制为
地图标记。
png

我将通过两个示例进行说明:

1.选择一个本地资产并将其大小动态更改为所需的大小,然后将其呈现在地图上(Flutter徽标图像);
2.在画布上绘制一些东西,并将其渲染为标记,但这可以是任何渲染小部件。
除此之外,您甚至可以将渲染窗口小部件转换为静态图像,因此也可以将其用作标记。

1.使用资产

首先,创建一种处理资产路径并接收大小的方法(
可以是宽度,高度或两者都可以,但是仅使用一个将保留
比率)。

import 'dart:ui' as ui;

Future<Uint8List> getBytesFromAsset(String path, int width) async {
  ByteData data = await rootBundle.load(path);
  ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);
  ui.FrameInfo fi = await codec.getNextFrame();
  return (await fi.image.toByteData(format: ui.ImageByteFormat.png)).buffer.asUint8List();
}

Then, just add it to your map using the right descriptor:

final Uint8List markerIcon = await getBytesFromAsset('assets/images/flutter.png', 100);
final Marker marker = Marker(icon: BitmapDescriptor.fromBytes(markerIcon));

This will produce the following for 50, 100 and 200 width respectively.

asset_example


2.使用画布

您可以使用画布绘制任何想要的东西,然后将其用作标记。在
下面将产生具有一些简单的圆框Hello world!的文字
吧。

因此,首先使用画布绘制一些东西:

Future<Uint8List> getBytesFromCanvas(int width, int height) async {
  final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
  final Canvas canvas = Canvas(pictureRecorder);
  final Paint paint = Paint()..color = Colors.blue;
  final Radius radius = Radius.circular(20.0);
  canvas.drawRRect(
      RRect.fromRectAndCorners(
        Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble()),
        topLeft: radius,
        topRight: radius,
        bottomLeft: radius,
        bottomRight: radius,
      ),
      paint);
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);
  painter.text = TextSpan(
    text: 'Hello world',
    style: TextStyle(fontSize: 25.0, color: Colors.white),
  );
  painter.layout();
  painter.paint(canvas, Offset((width * 0.5) - painter.width * 0.5, (height * 0.5) - painter.height * 0.5));
  final img = await pictureRecorder.endRecording().toImage(width, height);
  final data = await img.toByteData(format: ui.ImageByteFormat.png);
  return data.buffer.asUint8List();
}

然后以相同的方式使用它,但是这次提供的是您想要的任何数据(例如
宽度和高度),而不是资产路径。

final Uint8List markerIcon = await getBytesFromCanvas(200, 100);
final Marker marker = Marker(icon: BitmapDescriptor.fromBytes(markerIcon));

在这里,你有它。

2020-08-13