您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

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

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

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

您可以使用画布绘制任何想要的东西,然后将其用作标记。在 下面将产生具有一些简单的圆框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));

在这里,你有它。

Go 2022/1/1 18:22:33 有325人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶