Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Creating centered label for polygons #1220

Merged
merged 8 commits into from
Apr 21, 2022
Merged
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions lib/src/layer/polygon_layer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ class Polygon {
final bool isDotted;
final bool isFilled;
late final LatLngBounds boundingBox;
final String? label;
final TextStyle labelStyle;

Polygon({
required this.points,
Expand All @@ -47,6 +49,8 @@ class Polygon {
this.disableHolesBorder = false,
this.isDotted = false,
this.isFilled = false,
this.label,
this.labelStyle = const TextStyle(),
}) : holeOffsetsList = null == holePointsList || holePointsList.isEmpty
? null
: List.generate(holePointsList.length, (_) => []);
Expand Down Expand Up @@ -222,6 +226,42 @@ class PolygonPainter extends CustomPainter {
}
}

void _paintText(Canvas canvas, List<Offset> points) {
var maxDx = 0.0;
var minDx = double.infinity;
var dx = points.map((e) => e.dx).toList().fold<double>(0.0,
(previousValue, element) {
maxDx = max(maxDx, element);
minDx = min(minDx, element);
return previousValue + element;
}) /
points.length;
var dy = points.map((e) => e.dy).toList().fold<double>(
0.0, (previousValue, element) => previousValue + element) /
points.length;

final textSpan =
TextSpan(text: polygonOpt.label, style: polygonOpt.labelStyle);
final textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
maxLines: 1,
);
if (dx > 0) {
textPainter.layout(minWidth: 0, maxWidth: double.infinity);
dx = dx - textPainter.width / 2;
dy = dy - textPainter.height / 2;

if (maxDx - minDx > textPainter.width) {
textPainter.paint(
canvas,
Offset(dx, dy),
);
}
}
}

void _paintPolygon(Canvas canvas, Rect rect) {
final paint = Paint();

Expand Down Expand Up @@ -257,6 +297,10 @@ class PolygonPainter extends CustomPainter {
path.addPolygon(polygonOpt.offsets, true);
canvas.drawPath(path, paint);

if (polygonOpt.label != null) {
_paintText(canvas, polygonOpt.offsets);
}

_paintBorder(canvas);
}
}
Expand Down