createTextIcon static method

Future<BitmapDescriptor> createTextIcon(
  1. String text, {
  2. double width = 80,
  3. double horizontalPadding = 16,
  4. double verticalPadding = 8,
})

Creates a dynamic BitmapDescriptor marker with custom text.

The generated icon is a rounded black rectangle with white text inside.

Optional customization:

  • width (default: 80) – not currently used directly, can be integrated for layout control
  • horizontalPadding (default: 16)
  • verticalPadding (default: 8)

Returns a BitmapDescriptor that can be used in Marker.icon.

Implementation

static Future<BitmapDescriptor> createTextIcon(
  String text, {
  double width = 80,
  double horizontalPadding = 16,
  double verticalPadding = 8,
}) async {
  final recorder = ui.PictureRecorder();
  final canvas = Canvas(recorder);

  final painter = TextPainter(
    text: TextSpan(
      text: text,
      style: const TextStyle(
        fontSize: 25,
        color: Colors.white,
        backgroundColor: Colors.transparent, // We'll draw background manually
      ),
    ),
    textDirection: TextDirection.ltr,
  )..layout();

  final bgWidth = painter.width + horizontalPadding * 2;
  final bgHeight = painter.height + verticalPadding * 2;

  // Draw background rectangle with rounded corners
  final rect = Rect.fromLTWH(0, 0, bgWidth, bgHeight);
  final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(12));
  final paint = Paint()..color = Colors.black;
  canvas.drawRRect(rrect, paint);

  // Draw the text inside the padded area
  painter.paint(canvas, Offset(horizontalPadding, verticalPadding));

  final image = await recorder.endRecording().toImage(bgWidth.toInt(), bgHeight.toInt());
  final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  final bytes = byteData!.buffer.asUint8List();

  return BitmapDescriptor.fromBytes(bytes);
}