我想在 QML
中创建一个带有内部阴影的矩形,类似于 Photoshop
所做的事情:
QML
有 InnerShadow
但我无法实现这种效果。我得到的最接近的是这个
import QtQuick 2.0
import QtGraphicalEffects 1.0
Item {
id: root
width: 300
height: 300
Rectangle {
id: myRectangle
anchors.centerIn: parent
width: 100
height: 100
color: "grey"
}
InnerShadow {
anchors.fill: root
cached: true
horizontalOffset: 0
verticalOffset: 0
radius: 16
samples: 32
color: "#b0000000"
smooth: true
source: root
}
}
这是我从 this 得到的想法邮政。但是,此示例仅在 root
的大小明显大于 myRectangle
的情况下才有效,而我不希望这样。我需要例如一个 200x10
正方形,其中阴影均匀分布在矩形的边缘。我为 InnerShadow
属性尝试了各种值,但我无法接近我想要的效果。
这可以使用 QML
实现吗?
最佳答案
使用效果的“正确”方法 - 需要引号 - 应该是这样的:
import QtQuick 2.0
import QtGraphicalEffects 1.0
Item {
id: root
width: 300
height: 300
Item {
id: src
anchors.fill: parent
Rectangle {
id: myRectangle
anchors.centerIn: parent
width: 100
height: 100
color: "grey"
}
}
InnerShadow {
anchors.fill: src
cached: true
horizontalOffset: 0
verticalOffset: 0
radius: 16
samples: 32
color: "#b0000000"
smooth: true
source: src
}
}
如您所见,它与另一个问题中提出的解决方案略有不同。使用此代码,您仍然需要保留 2 个像素才能产生效果,从而产生白色边框(或任何背景颜色)。通过将 root
更改为 Rectangle
可以轻松解决此问题。
最终示例解决方案如下。很明显,您可以提取 root
组件(和相关的子组件)并将其放在 Component
或不同的 .qml
文件中供以后使用。
import QtQuick 2.4
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0
Window {
width: 200
height: 20
visible: true
Rectangle { // was Item
id: root
anchors.fill: parent
color: "grey"
Item {
id: src
anchors.fill: parent
Rectangle {
id: myRectangle
anchors.centerIn: parent
width: root.width - 2
height: root.height - 2
color: "lightgrey"
}
}
InnerShadow {
anchors.fill: src
cached: true
horizontalOffset: 0
verticalOffset: 0
radius: 16
samples: 32
color: "#b0000000"
smooth: true
source: src
}
}
}
最终代码示例的结果窗口:
关于c++ - QML 内阴影效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29517596/