项目中发现,使用Canvas绘制的文本、图片放大后 会变糊,边缘不清晰。经过调研,解决方案如下:
1.文本
使用canvas绘制的文本,经过放大4倍后效果图如下:
可以看到,放大后字体已经不清晰了。优化方案为:不使用Canvas绘制文本,使用Text组件。优化后效果如下:
下面展示一些 内联代码片
。
import QtQuick 2.2
import QtQuick.Window 2.15
import QtQuick.Controls 1.4
import QtQuick 2.15
import QtQuick.Shapes 1.15
Window {
id: root;
width: 640
height: 480
visible: true
title: qsTr("Hello World");
Rectangle {
id: rec;
anchors.fill: parent;
Rectangle {
id: rec_1;
width: rec.width;
height: rec.height / 4 * 3;
anchors.top: rec.top;
anchors.horizontalCenter: rec.horizontalCenter;
Text {
id: text;
text: qsTr("Text");
anchors.top: rec_1.top;anchors.left: rec_1.left;
font.family: "Arial";
font.pixelSize: 20;
}
Canvas {
id: canvas;
anchors.fill: rec_1;
onPaint: {
var ctx = getContext("2d");
//绘制文字
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Canvas", 100, 100);
}
}
transform: Scale {
id:scale;
xScale: 1;
yScale: 1;
origin.x: 0;
origin.y: 0;
}
}
Row {
width: rec.width;
height: rec.height / 4 * 1;
anchors.top: rec_1.bottom; anchors.topMargin: 30;
anchors.horizontalCenter: rec.horizontalCenter;
Button {
height: 30;
width: 100;
id: btn_up;
text: "放大";
onClicked: {
scale.xScale = scale.xScale + 0.5;
scale.yScale = scale.yScale + 0.5;
}
}
Button {
height: 30;
width: 100;
id: btn_down;
text: "缩小";
onClicked: {
scale.xScale = scale.xScale - 0.5;
scale.yScale = scale.yScale - 0.5;
}
}
}
}
}
2.线段
使用canvas绘制的线段,经过放大4倍后效果图如下:
线段其实已经出现了模糊,优化方案:不使用Canvas绘制,使用Shape。优化后效果如下:
左边为Shape绘制, 右边为Canvas绘制
下面展示一些 内联代码片
。
import QtQuick 2.2
import QtQuick.Window 2.15
import QtQuick.Controls 1.4
import QtQuick 2.15
import QtQuick.Shapes 1.15
Window {
id: root;
width: 640
height: 480
visible: true
title: qsTr("Hello World");
Rectangle {
id: rec;
anchors.fill: parent;
Rectangle {
id: rec_1;
width: rec.width;
height: rec.height / 4 * 3;
anchors.top: rec.top;
anchors.horizontalCenter: rec.horizontalCenter;
Shape {
anchors.fill: rec_1;
ShapePath {
startX: 30; startY: 50;
strokeColor: "blue";
strokeWidth: 2;
PathLine {x: 30; y: 200;}
}
}
Canvas {
id: canvas;
anchors.fill: rec_1;
onPaint: {
var ctx = getContext("2d");
//绘制线段
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(50, 200);
ctx.stroke();
}
}
transform: Scale {
id:scale;
xScale: 1;
yScale: 1;
origin.x: 0;
origin.y: 0;
}
}
Row {
width: rec.width;
height: rec.height / 4 * 1;
anchors.top: rec_1.bottom; anchors.topMargin: 30;
anchors.horizontalCenter: rec.horizontalCenter;
Button {
height: 30;
width: 100;
id: btn_up;
text: "放大";
onClicked: {
scale.xScale = scale.xScale + 0.5;
scale.yScale = scale.yScale + 0.5;
}
}
Button {
height: 30;
width: 100;
id: btn_down;
text: "缩小";
onClicked: {
scale.xScale = scale.xScale - 0.5;
scale.yScale = scale.yScale - 0.5;
}
}
}
}
}