flutter 实现文本贴图

117 阅读1分钟

关键代码

var maxWordHeight = 0.0;

    for(var i = 0; i < line.length;i++){
      var char = line.substring(i,i+1);
      final textPainter = TextPainter(
        text: TextSpan(text: char, style: textStyle.apply(
            color: Colors.black
        )),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(canvas, Offset(offsetX,0));
      offsetX+= (textPainter.width + wordSpace);
      maxWordHeight = max(maxWordHeight, textPainter.height);
    }

    canvas.drawImageRect(
      labelItem.image!,
      Rect.fromLTWH(0, 0, labelItem.image!.width.toDouble(), labelItem.image!.height.toDouble()),
      Rect.fromLTWH(0, 0, labelItem.width, maxWordHeight),
      Paint()
      ..blendMode = BlendMode.plus,
    );

或者

   canvas.saveLayer(Rect.fromLTWH(0, 0, labelItem.width, labelItem.height), Paint());
    for(var i = 0; i < line.length;i++){
      var char = line.substring(i,i+1);
      final textPainter = TextPainter(
        text: TextSpan(text: char, style: textStyle.apply(
            color: Colors.black
        )),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(canvas, Offset(offsetX,0));
      offsetX+= (textPainter.width + wordSpace);
      maxWordHeight = max(maxWordHeight, textPainter.height);
    }

    canvas.drawImageRect(
      labelItem.image!,
      Rect.fromLTWH(0, 0, labelItem.image!.width.toDouble(), labelItem.image!.height.toDouble()),
      Rect.fromLTWH(0, 0, labelItem.width, maxWordHeight),
      Paint()
      ..blendMode = BlendMode.srcIn,
    );
    canvas.restore();