【问题标题】:Gradient on a Rectangle's Border in QMLQML中矩形边框上的渐变
【发布时间】:2017-02-14 22:13:54
【问题描述】:

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

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

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
        }
    }
}

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

您好,
-m-

【问题讨论】:

  • QQuickPaintedItem 可能是最简单的。可能有一些方法可以使用 OpacityMask 着色器效果来破解它,或者在 Canvas 中绘制一次渐变帧,然后使用画布作为图像源,类似于此处解释的方法:stackoverflow.com/questions/35025386/…
  • 哇,看起来很复杂。我需要相当长的时间来消化它。谢谢!
  • 虽然我尽量避免使用QtGraphicalEffects,但OpacityMask确实很强大!

标签: qt qml qtquick2


【解决方案1】:

根据来自 cmets 的 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
            }
        }
    }
}

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

我希望我能在这方面帮助别人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    相关资源
    最近更新 更多