QML 中矩形边框上的渐变

Gradient on a Rectangle's Border in QML

我的这个问题对于其他语言和框架来说似乎很常见:

如何在矩形的边框上应用渐变? 到目前为止,我的解决方案是自定义组件,例如:

Item {
    id: root
    property int borderWidth
    property alias borderGradient: border.gradient
    property alias gradient: fill.gradient
    property alias color: fill.color
    property int radius

    Rectangle {
        id: border
        anchors.fill: parent
        radius: root.radius

        Rectangle {
            id: fill
            anchors.fill: parent
            anchors.margins: root.borderWidth
            radius: root.radius * width / border.width / 2
        }
    }
}

然而,这不允许我将矩形的颜色设置为 'transparent',这很可悲,但我可以接受。我仍然想知道,是否有更优雅的方法(除了直接使用 Context2D 或 QSG...)

你好,
-m-

根据评论中 ddriver 的建议,我整理了一个矩形的工作示例,您可以在其中使用 OpacityMask 为边框设置渐变。 我在某处听说 QtGraphicalEffects 的性能很差,所以我可能会在未来尝试一个没有的,但对于那些不关心的人来说,这是一个有效的例子:

import QtQuick 2.0
import QtGraphicalEffects 1.0

Rectangle {
    id: root
    property Gradient borderGradient
    property int borderWidth: 0


    Loader {
        id: loader
        active: borderGradient
        anchors.fill: parent
        sourceComponent: border
    }

    Component.onCompleted: console.log(loader.active)

    Component {
        id: border
        Item {
            Rectangle {
                id: borderFill
                radius: root.radius
                anchors.fill: parent
                gradient: root.borderGradient
                visible: false
            }

            Rectangle {
                id: mask
                radius: root.radius
                border.width: root.borderWidth
                anchors.fill: parent
                color: 'transparent'
                visible: false   // otherwise a thin border might be seen.
            }

            OpacityMask {
                id: opM
                anchors.fill: parent
                source: borderFill
                maskSource: mask
            }
        }
    }
}

它只会在需要时(当设置了 borderGradient 时)使用 OpacityMask,否则它的行为就像一个普通的矩形。

我希望我可以帮助别人。