generateImageBytes static method

Future<List<int>> generateImageBytes({
  1. required String content,
  2. CFont font = CFont.tss16,
  3. CRotation rotation = CRotation.rotation_0,
  4. bool? bold,
  5. int alpha = 255,
  6. Uint8List? familyBytes,
})

Implementation

static Future<List<int>> generateImageBytes({
  required String content,
  CFont font = CFont.tss16,
  CRotation rotation = CRotation.rotation_0,
  bool? bold,
  int alpha = 255,
  Uint8List? familyBytes,
}) async {
  final adjustedAlpha = alpha.clamp(0, 255);

  // 加载字体
  final TextStyle textStyle = await _loadTextStyle(font, bold, adjustedAlpha, familyBytes);

  // 测量文字
  final TextPainter textPainter = TextPainter(
    text: TextSpan(text: content, style: textStyle),
    textDirection: TextDirection.ltr,
  )
    ..layout();

  // 计算画布尺寸
  late int canvasWidth;
  late int canvasHeight;
  if (rotation == CRotation.rotation_90 || rotation == CRotation.rotation_270) {
    canvasWidth = textPainter.height.ceil();
    canvasHeight = textPainter.width.ceil();
  } else {
    canvasWidth = textPainter.width.ceil();
    canvasHeight = textPainter.height.ceil();
  }

  // 添加内边距(避免文字贴边)
  const int padding = 2;
  canvasWidth += padding * 2;
  canvasHeight += padding * 2;

  // 绘制文字
  final ui.Image textImage = await _drawText(textPainter, canvasWidth, canvasHeight, rotation, padding);

  // 抖动处理(alpha < 255 时启用)
  final ui.Image finalImage = adjustedAlpha < 255 ? await _ditheredImage(textImage) : textImage;

  // 转为PNG字节(List<int>,供外部传入CTextCanvas)
  final ByteData? pngData = await finalImage.toByteData(format: ui.ImageByteFormat.png);
  if (pngData == null) throw StateError("图片转PNG失败");

  final imageBytes = pngData.buffer.asUint8List().toList();
  print("图片字节生成完成,长度:${imageBytes.length}");
  return imageBytes;
}