Last active
November 12, 2020 10:03
-
-
Save s0nerik/9471a6fd23b1e4226aa93c911faab377 to your computer and use it in GitHub Desktop.
Flutter cluster bitmap rendering example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/[email protected]' | |
: 'assets/map/[email protected]', | |
); | |
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