【问题标题】:How i can use FontLoader qml object in canvas qml element?我如何在画布 qml 元素中使用 FontLoader qml 对象?
【发布时间】:2018-04-26 14:05:07
【问题描述】:

您好,我想在 Canvas 元素中使用 Fontloader qml 对象中设置的字体,其中我有一个弯曲的文本。有可能做到吗?一般来说,可以更改画布文本的字体系列吗? 这是我的代码:

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


        FontLoader { id: webFont;name: "OpenSans"; source: "qrc:/OpenSans-Bold.ttf" }

        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 OpenSans'
              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);
          }
        }
    }

我想使用我按照说明设置的 Verdana 字体:

ctx.font='50px Verdana'

字体设置为 FontLoader { id: webFont;来源:“qrc:/OpenSans-Bold.ttf”}

我该怎么做?

【问题讨论】:

  • 你试过ctx.font='50px OpenSans'吗?
  • 可以,但是不行!!
  • 您具体尝试了什么?如在,请更新您的代码。
  • 我已经更新了代码,当我运行应用程序时,我得到这个错误 Context2D: The font family specified are invalid: OpenSans 。我还重命名了“OpenSans”中 FontLoader 元素的属性名称
  • 如果从FontLoader 中删除name: "OpenSans" 并添加Component.onCompleted: print(name),会得到什么?

标签: javascript qt canvas qml


【解决方案1】:

正如你在cmets中所说,问题确实是字体名称中的空格。

如上所述in the doc

注意:font-size 和 font-family 属性是强制性的,并且必须 按上面显示的顺序排列。此外,字体系列 名称中带有空格的必须用引号引起来。

所以问题应该通过加载字体来解决

FontLoader { id: webFont; source: "qrc:/OpenSans-Bold.ttf" }

并使用

ctx.font='50px "Open Sans"'

甚至更好:

ctx.font='50px "%1"'.arg(webFont.name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2015-08-10
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多