【问题标题】:Is it possible to apply a color Gradient to Text in QML?是否可以在 QML 中将颜色渐变应用于文本?
【发布时间】:2015-03-31 21:27:31
【问题描述】:

是否可以在 QML 中对文本应用颜色渐变?如果是这样,怎么做?如果不是,那么实现相同效果的可接受方式是什么?

【问题讨论】:

    标签: qt qml gradient styling


    【解决方案1】:

    您可以使用LinearGradient QML 类型。

    import QtQuick 2.4
    import QtQuick.Window 2.2
    import QtGraphicalEffects 1.0
    
    Window
    {
        visible: true
        height: 500
        width: 500
        Text {
            id: text
            font.pointSize: 55
            anchors.centerIn: parent
            text: "Hello World!"
            visible: false
        }
        LinearGradient  {
            anchors.fill: text
            source: text
            gradient: Gradient {
                GradientStop { position: 0; color: "yellow" }
                GradientStop { position: 1; color: "red" }
            }
        }
    }
    

    【讨论】:

    • 赞成。如果没有可用的着色器知识,这是最简单的方法。奇怪的是十个小时左右没有人想出这个!
    • 同意@BaCaRoZzo,这个解决方案更简单,更可取
    【解决方案2】:

    可以使用Item layers 例如:

    import QtQuick 2.3
    import QtQuick.Window 2.0
    import QtGraphicalEffects 1.0
    
    Window {
        width: 400
        height: 300
        visible: true
        Rectangle {
            id: gradientRect;
            width: 10
            height: 10
            gradient: Gradient {
                GradientStop { position: 0; color: "yellow" }
                GradientStop { position: 1; color: "red" }
            }
            visible: false;
            layer.enabled: true;
            layer.smooth: true
        }
    
        Text {
            id: txt
            anchors.centerIn: parent
            text: "Hello, world"
            font.pixelSize: 64
            layer.enabled: true
            layer.samplerName: "maskSource"
            layer.effect: ShaderEffect {
                property var colorSource: gradientRect;
                fragmentShader: "
                            uniform lowp sampler2D colorSource;
                            uniform lowp sampler2D maskSource;
                            uniform lowp float qt_Opacity;
                            varying highp vec2 qt_TexCoord0;
                            void main() {
                                gl_FragColor =
                                    texture2D(colorSource, qt_TexCoord0)
                                    * texture2D(maskSource, qt_TexCoord0).a
                                    * qt_Opacity;
                            }
                        "
            }
        }
    }
    

    查看here 了解更多示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2022-12-15
      • 2020-09-26
      • 2018-06-10
      • 1970-01-01
      • 2020-05-29
      • 2015-06-02
      相关资源
      最近更新 更多