如何在 QML 中创建带孔的形状?
How to create a shape with a hole in QML?
我想创建一种由黑色区域和孔组成的遮罩层。通过孔应该可以看到背景。在最简单的版本中,我只是一个覆盖整个屏幕的矩形,中间有一个开口。如下图示例所示。
我的第一个方法是使用 QML 的 Context2D 功能:https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = "black"
ctx.beginPath();
ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
ctx.fill();
}
如果孔正好居中且边框大小相同,则可以使用带边框的透明矩形:
Rectangle {
anchors.fill: parent
color: "transparent"
border.color: "black"
border.width: 50
}
我通过重新阅读 Qt 文档找到了自己的解决方案。有一个函数可以在给定的 canvas 内创建透明矩形,称为 "clearRect(...)":https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clearRect-method
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = "black"
ctx.beginPath();
ctx.fillRect(0, 0, 1000, 600);
ctx.fill();
ctx.clearRect(10, 10, 600, 100)
}
对于更高级的形状OpacityMask suggested by Frank Osterfeld绝对是解决这个问题的方法。但对于矩形,我认为我的解决方案更直接。
我想创建一种由黑色区域和孔组成的遮罩层。通过孔应该可以看到背景。在最简单的版本中,我只是一个覆盖整个屏幕的矩形,中间有一个开口。如下图示例所示。
我的第一个方法是使用 QML 的 Context2D 功能:https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = "black"
ctx.beginPath();
ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
ctx.fill();
}
如果孔正好居中且边框大小相同,则可以使用带边框的透明矩形:
Rectangle {
anchors.fill: parent
color: "transparent"
border.color: "black"
border.width: 50
}
我通过重新阅读 Qt 文档找到了自己的解决方案。有一个函数可以在给定的 canvas 内创建透明矩形,称为 "clearRect(...)":https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clearRect-method
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = "black"
ctx.beginPath();
ctx.fillRect(0, 0, 1000, 600);
ctx.fill();
ctx.clearRect(10, 10, 600, 100)
}
对于更高级的形状OpacityMask suggested by Frank Osterfeld绝对是解决这个问题的方法。但对于矩形,我认为我的解决方案更直接。