我想在qml中创建弯曲的文字吗?我可以导入一个JavaScript库来做到这一点吗?

javascript - 我如何在QML Canvas元素中创建弯曲的文本?-LMLPHP

我的想法是,有可能使用canvas元素,但是我不知道该怎么做……这是一个好主意?

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Canvas{

      anchors.fill: parent

      onPaint: {
          var ctx = getContext("2d");
          ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
          ctx.fillRect(0, 0, width, height);
          //how i can create curved text???

      }

    }
}

最佳答案

您好,我尝试将代码插入@folibis发布的链接中,效果很好!!!
这是代码:

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Canvas{

        property string nameFont: webFont.name

        function drawTextAlongArc(context, str, centerX, centerY, radius, angle)
        {

            context.save();
            context.translate(centerX, centerY);
            context.rotate(-1 * angle / 2);
            context.rotate(-1 * (angle / str.length) / 2);
            for (var n = 0; n < str.length; n++) {
                context.rotate(angle / str.length);
                context.save();
                context.translate(0, -1 * radius);
                var char1 = str[n];
                context.fillText(char1, 0, 0);
                context.restore();
            }
            context.restore();

        }


      anchors.fill: parent
      onPaint: {

          var ctx = getContext("2d");
          ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
          ctx.fillRect(0, 0, width, height);


          ctx.font='50px Verdana'

          //ctx.font = '30px Courier New'
          ctx.textAlign = "center";

          var centerX = width / 2;
          var centerY = height/2; //height - 30;
          var angle   = Math.PI * 0.8; // radians
          var radius  = 180;
          ctx.fillStyle="#000000"
          drawTextAlongArc(ctx, "Hello World", centerX, centerY, radius, angle);

      }
    }
}

10-06 09:38