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

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

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

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 prec = await ui.instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width);  ui.frameInfo fi = await prec.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.


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));

在这里,你有它。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4886447.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存