import QtQuick 2.4 import QtQuick.Controls 2.5 import QtQuick.Window 2.3 ApplicationWindow { visible: true width: 800 height: 600 title: "Drawing Board Example" Item { width: 400 height: 400 property int gridSize: 20 property int scaleFactor: 100 Canvas { id: canvas anchors.fill: parent onPaint: { var ctx = getContext("2d"); var width = canvas.width; var height = canvas.height; // 清除画布 ctx.clearRect(0, 0, width, height); // 绘制网格线 ctx.strokeStyle = "black"; for (var x = 0; x <= width; x += parent.gridSize) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke(); } for (var y = 0; y <= height; y += parent.gridSize) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke(); } } } MouseArea { anchors.fill: parent property int gridSize: parent.gridSize property int scaleFactor: parent.scaleFactor onWheel: { // 根据滚轮事件的delta属性,计算缩放比例 parent.scaleFactor += wheel.angleDelta.y / 120; parent.scaleFactor = Math.max(parent.scaleFactor, 10); // 最小值为10% // 根据缩放比例重新计算gridSize和canvas的宽度和高度 parent.gridSize = parent.scaleFactor / 5; canvas.width = width * parent.scaleFactor / 100; canvas.height = height * parent.scaleFactor / 100; canvas.requestPaint(); } } } }这段代码的功能是实现一个利用鼠标滚轮的可伸缩的网格画布,请优化这段代码,使其的网格线更细,画布出现的初始位置相对更向中间
时间: 2024-03-17 21:40:57 浏览: 49
以下是修改后的代码,主要将原先绘制网格线的线宽改小,初始位置偏移量也做了调整:
```qml
import QtQuick 2.4
import QtQuick.Controls 2.5
import QtQuick.Window 2.3
ApplicationWindow {
visible: true
width: 800
height: 600
title: "Drawing Board Example"
Item {
width: 400
height: 400
property int gridSize: 20
property int scaleFactor: 100
Canvas {
id: canvas
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
var width = canvas.width;
var height = canvas.height;
// 清除画布
ctx.clearRect(0, 0, width, height);
// 绘制网格线
ctx.strokeStyle = "black";
ctx.lineWidth = 0.2; // 将线宽改小
for (var x = -width/2; x <= width/2; x += parent.gridSize) {
ctx.beginPath();
ctx.moveTo(x, -height/2);
ctx.lineTo(x, height/2);
ctx.stroke();
}
for (var y = -height/2; y <= height/2; y += parent.gridSize) {
ctx.beginPath();
ctx.moveTo(-width/2, y);
ctx.lineTo(width/2, y);
ctx.stroke();
}
}
}
MouseArea {
anchors.fill: parent
property int gridSize: parent.gridSize
property int scaleFactor: parent.scaleFactor
onWheel: {
// 根据滚轮事件的delta属性,计算缩放比例
parent.scaleFactor += wheel.angleDelta.y / 120;
parent.scaleFactor = Math.max(parent.scaleFactor, 10); // 最小值为10%
// 根据缩放比例重新计算gridSize和canvas的宽度和高度
var newGridSize = parent.scaleFactor / 5;
var newWidth = width * parent.scaleFactor / 100;
var newHeight = height * parent.scaleFactor / 100;
var xDiff = (newWidth - width) / 2; // 计算横向偏移量
var yDiff = (newHeight - height) / 2; // 计算纵向偏移量
parent.gridSize = newGridSize;
canvas.width = newWidth;
canvas.height = newHeight;
canvas.x -= xDiff; // 调整canvas的位置
canvas.y -= yDiff;
canvas.requestPaint();
}
}
}
}
```
修改后的代码将网格线的线宽从原先的 0.5 改为了 0.2 ,使得网格线更细。同时,在计算新的画布宽度和高度时,加入了横向和纵向偏移量的计算,使得画布的初始位置相对更向中间。
阅读全文