rasterize method
Since the Paragraph rasterizing to the Canvas, and the getting of the Image bytes are async functions
Implementation
Future<void> rasterize() async {
if (_displayLineMetrics.isNotEmpty) {
_image = await _picture.toImage(_width, _totalHeight);
var byteData =
(await _image.toByteData(format: ui.ImageByteFormat.rawUnmodified))!;
// loop over each line of text in the paragraph and create a TxSprite
for (var line in _displayLineMetrics) {
int tlX = line.left.toInt();
int tlY = (line.baseline - line.ascent).toInt();
int lineWidth = line.width.toInt();
int lineHeight = (line.ascent + line.descent).toInt();
var linePixelData = Uint8List(lineWidth * lineHeight);
for (int i = 0; i < lineHeight; i++) {
// take one row of the source image byteData, remembering it's in RGBA so 4 bytes per pixel
var sourceRow = byteData.buffer
.asUint8List(((tlY + i) * _width + tlX) * 4, lineWidth * 4);
for (int j = 0; j < lineWidth; j++) {
// take only every 4th byte because the source buffer is RGBA
// and map it to palette index 1 if it's 128 or bigger (monochrome palette only, and text rendering will be anti-aliased)
linePixelData[i * lineWidth + j] = sourceRow[4 * j] >= 128 ? 1 : 0;
}
}
// make a Sprite out of the line and add to the list
_lines.add(TxSprite(
msgCode: _msgCode,
width: lineWidth,
height: lineHeight,
numColors: 2,
paletteData: _getPalette().data,
pixelData: linePixelData));
}
}
}