思路:canvas画笔操作频繁会比较耗时,利用drawImage方式绘制预加载的文字图像,把绘制过的文字部分像素数据缓存到一个键值列表里,重复绘制时直接取键值列表里的像素数据绘制到canvas目标区域上
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Rectangle {
anchors.fill: parent
Rectangle {
id: topItem
color: "#cccccc"
anchors.top: parent.top
height: 50
anchors.left: parent.left
anchors.right: parent.right
Row {
anchors.fill: parent
Button {
text: qsTr("测试1")
onClicked: {
showCanvas.target = "测试1";
showCanvas.requestPaint()
}
}
Button {
text: qsTr("测试2")
onClicked: {
showCanvas.target = "测试2";
showCanvas.requestPaint()
}
}
}
}
Rectangle {
anchors.top: topItem.bottom
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
Canvas {
id: showCanvas
anchors.fill: parent
property var data: Object
property string target: ""
onPaint: {
var ctx = getContext("2d");
ctx.clearRect(0,0,width,height);
if(target === "测试1") {
if("测试1" in data) {
ctx.drawImage(data["测试1"],0,0);
}
else {
ctx.save();
ctx.strokeStyle = "red";
var text = "测试1";
var textSize = calTextSize.getTextSize(text);
ctx.font = calTextSize.fontToString(calTextSize.font);
ctx.strokeText(text,0,textSize["height"]);
var test1Data = ctx.getImageData(0,0,textSize["width"],textSize["height"] + textSize["height"]/10);
console.log("textSize[height]:",textSize["height"]);
console.log("test1Data.height:",test1Data.height);
data["测试1"] = test1Data;
ctx.restore();
}
}
else if(target === "测试2"){
if("测试2" in data) {
ctx.drawImage(data["测试2"],50,50);
}
else {
ctx.save();
ctx.strokeStyle = "green";
var text2 = "测试2";
var textSize2 = calTextSize.getTextSize(text2);
ctx.font = calTextSize.fontToString(calTextSize.font);
ctx.strokeText(text2,50,50+textSize2["height"]);
var test2Data = ctx.getImageData(50,50,textSize2["width"],textSize2["height"] + textSize["height"]/10);
data["测试2"] = test2Data;
ctx.restore();
}
}
}
}
}
}
Text {//绘制刻度线上的文字时计算文字宽高
id: calTextSize
visible: false
font.pixelSize: 100
function fontToString(font) {
return font.pixelSize + "px " + font.family;
}
function getTextWidth(text,pixSize)
{
calTextSize.font.pixelSize = pixSize
calTextSize.text = text
return calTextSize.contentWidth
}
function getTextHeight(text,pixSize)
{
calTextSize.font.pixelSize = pixSize
calTextSize.text = text
return calTextSize.contentHeight
}
function getTextSize(text,pixSize)
{
calTextSize.font.pixelSize = pixSize
calTextSize.text = text
var map = []
map["width"] = calTextSize.contentWidth
map["height"] = calTextSize.contentHeight
return map
}
}
}