flutter_scene icon indicating copy to clipboard operation
flutter_scene copied to clipboard

how to add text label ?

Open wangcker opened this issue 10 months ago • 1 comments

as subject

wangcker avatar Apr 08 '25 11:04 wangcker

this is my code .but The effect is not ideal


class GlUtil {
  Future<Node> createTextNode(String text) async {
    Node result = Node(
      name: 'text_node_$text',
      localTransform: vm.Matrix4.identity(),
    );

    gpu.Texture texture = await createTextTexture(text, const Size(72, 48));
    CuboidGeometry cuboidGeometry = CuboidGeometry(vm.Vector3(1.2, 0.8, 0.01));
    //UnskinnedGeometry unskinnedGeometry = UnskinnedGeometry();

    PhysicallyBasedMaterial unlitMaterial =
        PhysicallyBasedMaterial(baseColorTexture: texture);
    //unlitMaterial.baseColorFactor = vm.Colors.transparent;

    result.mesh = Mesh(cuboidGeometry, unlitMaterial);

    result.localTransform.translate(vm.Vector3(0, 0.4, 1));
    result.localTransform.rotateX(pi);
    return result;
  }

  Future<gpu.Texture> createTextTexture(String text, Size size) async {
    ui.Image? image = await getCanvasImage(text, size);

    return gpuTextureFromImage(image!);
  }

  Future<ui.Image?> getCanvasImage(String str, Size size) async {
    final recorder = ui.PictureRecorder();

    var newCanvas = Canvas(recorder);

    final textPainter = TextPainter(
      text: TextSpan(
        text: str,
        style: const TextStyle(
            color: Colors.black, fontSize: 24, overflow: TextOverflow.ellipsis),
      ),
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(minWidth: 0, maxWidth: size.width);
    newCanvas.drawColor(Colors.white, BlendMode.clear);
    textPainter.paint(
        newCanvas,
        Offset((size.width - textPainter.width) / 2,
            (size.height - textPainter.height) / 2));

    final picture = recorder.endRecording();

    var res = await picture.toImage(size.width.toInt(), size.height.toInt());

    return res;
  }
}

wangcker avatar Apr 16 '25 02:04 wangcker