Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Last active November 12, 2020 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s0nerik/9471a6fd23b1e4226aa93c911faab377 to your computer and use it in GitHub Desktop.
Save s0nerik/9471a6fd23b1e4226aa93c911faab377 to your computer and use it in GitHub Desktop.
Flutter cluster bitmap rendering example
BitmapDescriptor _stationPin;
ui.Image _clusterBgImage;
Future<BitmapDescriptor> _getClusterBitmap(
BuildContext context,
MapCluster cluster,
) async {
if (!cluster.isCluster && _stationPin != null) {
return _stationPin;
}
final density = MediaQuery.of(context).devicePixelRatio;
final canvasScale = 1 / 3 * density;
final pictureRecorder = ui.PictureRecorder();
final canvas = Canvas(pictureRecorder);
canvas.scale(canvasScale);
final text = cluster.isCluster ? cluster.children.length.toString() : null;
ui.Image bgImage;
if (text != null && _clusterBgImage != null) {
bgImage = _clusterBgImage;
} else {
final bgImageData = await rootBundle.load(
text != null
? 'assets/map/cluster_icon@3x.png'
: 'assets/map/gas_station_icon@3x.png',
);
bgImage = await decodeImageFromList(bgImageData.buffer.asUint8List());
}
paintImage(
canvas: canvas,
image: bgImage,
rect: Rect.fromLTRB(
0,
0,
bgImage.width.toDouble(),
bgImage.height.toDouble(),
),
);
if (text != null) {
final painter = TextPainter(textDirection: TextDirection.ltr);
painter.text = TextSpan(
text: text,
style: TextStyle(
fontSize: bgImage.width / 4,
color: Colors.white,
fontWeight: FontWeight.normal,
),
);
painter.layout();
painter.paint(
canvas,
Offset(
bgImage.width / 2 - painter.width / 2 + 3,
bgImage.height / 5,
),
);
}
final img = await pictureRecorder.endRecording().toImage(
(bgImage.width * canvasScale).toInt(),
(bgImage.height * canvasScale).toInt(),
);
final data = await img.toByteData(format: ui.ImageByteFormat.png);
final result = BitmapDescriptor.fromBytes(data.buffer.asUint8List());
if (text == null) {
_stationPin ??= result;
} else {
_clusterBgImage ??= bgImage;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment