1. 程式人生 > >qml學習---------------利用Canvas繪製文字

qml學習---------------利用Canvas繪製文字

在利用Canvas繪製文字的時候,可以指定文字不同的風格。
Context2D中和文字相關的方法有3個: fillText() , strokeText() , text();

使用方法就下面兩種:
ctx.beginPath();
ctx.text(“stroken text” ,100 , 100);
ctx.stroke();

或者是另外的一種使用方法:
ctx.strokeText(“stroken text” , 200 ,100);

下面就通過一個具體的例子來學習下。

import QtQuick 2.2

Canvas{

    width: 530;
    height: 300
; id: root; onPaint: { var ctx = getContext("2d"); ctx.lineWidth = 2; ctx.strokeStyle = "red"; ctx.font = " 42px sans-serif"; var gradient = ctx.createLinearGradient(0,0, width , height); gradient.addColorStop( 0.0 , Qt.rgba(0 , 1 ,0 , 1)); gradient.addColorStop
(1.0 , Qt.rgba(0,0, 1 , 1)); ctx.fillStyle = gradient; ctx.beginPath(); ctx.text("Fill Text on Path" , 10 , 50); ctx.fill(); // 設定 ↑ 的text的風格為fill ctx.fillText("Fill Text" , 10 , 100); ctx.beginPath(); ctx.text("Stroke Text on Path" , 10 , 150); ctx.stroke
(); //設定 ↑ 的text風格為stroke ctx.strokeText("Stroke Text" , 10 , 200); ctx.beginPath(); ctx.text("Stroke and Fill Text on Path" , 10 , 250 ); ctx.stroke(); ctx.fill(); } }