0
votes

Hello i want to use the font set into Fontloader qml object in a Canvas element , where i have a curved text. It's possible do it? In general change font family of canvas text it's possible ? This is my code:

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

I want to use instead of Verdana font, that i setted with the instruction :

ctx.font='50px Verdana'

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

How i can do it ?

1
Did you try ctx.font='50px OpenSans'?Mitch
yes, but don't work!!pablodepas87
What did you try, specifically? As in, please update your code.Mitch
I have updated the code , when i run the application i get this error Context2D: The font families specified are invalid: OpenSans . I have also renamed the proprerty name of the FontLoader element in 'OpenSans'pablodepas87
What do you get if you remove name: "OpenSans" from the FontLoader and add Component.onCompleted: print(name)?Mitch

1 Answers

1
votes

As you said in the comments, the problem is indeed the space in the font name.

As mentioned in the doc:

Note: The font-size and font-family properties are mandatory and must be in the order they are shown in above. In addition, a font family with spaces in its name must be quoted.

So the problem should be fixed by loading your font with

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

and using

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

or even better:

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