iconToBytes static method
Converts an IconData into PNG bytes by drawing the glyph on a canvas. Produces a sharp result using an internal scale factor.
Implementation
static Future<Uint8List?> iconToBytes(
IconData iconData, {
double size = 24.0,
Color color = Colors.black,
}) async {
try {
// The higher the scale, the better the quality; using a very high scale may
// impact performance!
final double scale = 3.0;
final double scaledSize = size * scale;
final recorder = ui.PictureRecorder();
final canvas = Canvas(recorder);
final textPainter = TextPainter(textDirection: TextDirection.ltr);
// Text using the icon data
textPainter.text = TextSpan(
text: String.fromCharCode(iconData.codePoint),
style: TextStyle(
fontSize: scaledSize,
fontFamily: iconData.fontFamily,
package: iconData.fontPackage,
color: color,
fontFeatures: [const FontFeature.enable('liga')], // Use ligatures :)
),
);
textPainter.layout();
final double dx = (scaledSize - textPainter.width) / 2;
final double dy = (scaledSize - textPainter.height) / 2;
textPainter.paint(canvas, Offset(dx, dy));
final picture = recorder.endRecording();
final img = await picture.toImage(scaledSize.toInt(), scaledSize.toInt());
final byteData = await img.toByteData(format: ui.ImageByteFormat.png);
return byteData?.buffer.asUint8List();
} catch (e) {
debugPrint('Error converting icon to bytes: $e');
return null;
}
}