2

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

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

上述方法创建了倒三角形,我需要创建一个标记形状。我该如何实现?

4

2 回答 2

0

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

于 2020-05-23T14:29:18.080 回答
0

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

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

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

于 2022-02-22T17:30:22.500 回答