render method

Future<ZplRaster> render(
  1. ZplGenerator generator, {
  2. int? widthDots,
  3. int? heightDots,
  4. double scale = 1.0,
})

Paints generator white-first at widthDots x heightDots, drawn at scale pixels per dot. These default to the configuration's printWidth and labelLength, else 406 x 609. Throws an ArgumentError when scale is not finite or not greater than 0.

Implementation

Future<ZplRaster> render(
  ZplGenerator generator, {
  int? widthDots,
  int? heightDots,
  double scale = 1.0,
}) async {
  if (!scale.isFinite || scale <= 0) {
    throw ArgumentError.value(
      scale,
      'scale',
      'must be finite and greater than 0',
    );
  }
  final widthDotsValue = widthDots ?? generator.config.printWidth ?? 406;
  final heightDotsValue = heightDots ?? generator.config.labelLength ?? 609;
  final size = ui.Size(widthDotsValue.toDouble(), heightDotsValue.toDouble());
  final width = _pixels(widthDotsValue, scale);
  final height = _pixels(heightDotsValue, scale);
  final pixelSize = ui.Size(width.toDouble(), height.toDouble());

  final recorder = ui.PictureRecorder();
  final canvas = ui.Canvas(recorder, ui.Offset.zero & pixelSize);
  canvas.drawRect(
    ui.Offset.zero & pixelSize,
    ui.Paint()..color = const ui.Color(0xFFFFFFFF),
  );
  canvas.scale(scale);
  ZplCanvasPainter(generator: generator).paint(canvas, size);
  final picture = recorder.endRecording();
  // Both are native handles: dispose them whatever fails, including
  // `toImage` itself (an empty size throws "Invalid image dimensions").
  ui.Image? image;
  try {
    image = await picture.toImage(width, height);
    final pngData = await image.toByteData(format: ui.ImageByteFormat.png);
    final rawData = await image.toByteData(
      format: ui.ImageByteFormat.rawRgba,
    );
    return ZplRaster(
      png: pngData!.buffer.asUint8List(
        pngData.offsetInBytes,
        pngData.lengthInBytes,
      ),
      width: width,
      height: height,
      inkRatio: _inkRatio(rawData!, width * height),
      scale: scale,
    );
  } finally {
    image?.dispose();
    picture.dispose();
  }
}