如何绘制标记? 就像使用画布的谷歌地图中的标记一样



我需要使用画布绘制一个自定义标记,到目前为止,我绘制了一个反三角形形状。您对如何绘制标记形状有任何想法吗?

class DrawTriangle extends CustomPainter {
Paint _paint;
DrawTriangle() {
_paint = Paint()
..color = Colors.green
..style = PaintingStyle.fill;
}
@override
void paint(Canvas canvas, Size size) {
var path = Path();
path.moveTo(size.width, size.height);
path.lineTo(size.width + 100, size.height - 100);
path.lineTo(size.width - 100, size.height - 100);
path.close();
canvas.drawPath(path, _paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
Future<Uint8List> getBytesFromCanvas(
int width, int height, Color color) async {
final PictureRecorder pictureRecorder = PictureRecorder();
final Canvas canvas = Canvas(pictureRecorder);
CustomPainter painter = DrawTriangle();
painter.paint(canvas, Size(100.0,100.0));
final img = await pictureRecorder.endRecording().toImage(width, height);
final data = await img.toByteData(format: ImageByteFormat.png);
return data.buffer.asUint8List();
}

上面的方法创建反三角形,我需要创建一个标记形状。 我如何实现这一点?

这像素并不完美,但它对我有用(特别是如果标记大小不是太大(

import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

Future<BitmapDescriptor> getMarkerFromCanvas(
int customNum, double width, double height, Color color) async {
final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
final Canvas canvas = Canvas(pictureRecorder);
final Paint paint = Paint()..color = color;
final Radius radius = Radius.circular(width / 2);
canvas.clipPath(Path()
..moveTo(0, height / 2.7)
..lineTo(width / 2, height.toDouble())
..lineTo(width.toDouble(), height / 2.7)
..arcToPoint(
Offset(width.toDouble(), 0),
)
..arcToPoint(const Offset(0, 0)));
canvas.drawRRect(
RRect.fromRectAndCorners(
Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble()),
topLeft: radius,
topRight: radius,
bottomLeft: radius,
bottomRight: radius,
),
paint);
final img = await pictureRecorder
.endRecording()
.toImage(width.toInt(), height.toInt());
final data = await img.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(data!.buffer.asUint8List());
}

您可以异步调用此函数,然后设置状态并直接在GoogleMap标记中使用存储的返回BitmapDescriptor,即:Marker( icon: _theReturnedValue);

为什么要使用自定义画家 您也可以将图像用于相同的任务。我为你找到了这篇文章。希望我能帮到你。

最新更新