如何在图像中创建渐变不透明度? - QML

时间:2018-01-27 04:50:22

标签: qt qml qt5 gradient opacity

如何在qml中使图像淡入淡出?我该如何达到这个效果?在这里,我附上了我希望它看起来的图像

enter image description here

2 个答案:

答案 0 :(得分:4)

可能的解决方案是使用OpacityMask作为来源<{3}}

import QtQuick 2.9
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0

Window {
    visible: true
    width: 600
    height: 600
    title: qsTr("Hello World")
    Image {
        id: input
        source: "input.jpg"
        anchors.fill: parent

        OpacityMask {
            source: mask
            maskSource: input
        }

        LinearGradient {
            id: mask
            anchors.fill: parent
            gradient: Gradient {
                GradientStop { position: 0.2; color: "transparent"}
                GradientStop { position: 0.5; color: "white" }
            }
        }
    }
}

输入:

LinearGradient

输出:

enter image description here

答案 1 :(得分:1)

虽然公认的解决方案达到了预期的效果,但实际上并没有在原始图像中创建不透明度渐变(这正是我所需要的)。它只是将 LinearGradient 覆盖在图像顶部; OpacityMask 没有做任何事情,可以从该示例中删除。图片底部的白色来自 LinearGradient,而不是背景。

以下是如何在原始图像中创建不透明度渐变的示例。请注意,“源图像”(在本例中为 Rectangle)和 LinearGradient 的可见性都是 false

import QtQuick 2.9
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")
    
    // The background, to ensure it's working
    Rectangle {
        color: "red"
        anchors.fill: parent
    }

    // The "source image"
    Rectangle {
        id: blueBox
        color: "blue"
        anchors.fill: parent
        opacity: 0.5
        visible: false
    }
    
    LinearGradient {
        id: mask
        anchors.fill: blueBox
        gradient: Gradient {
            GradientStop {
                position: 0.2
                color: "transparent"
            }
            GradientStop {
                position: 0.5
                color: "white"
            }
        }
        visible: false
    }
    
    OpacityMask {
        anchors.fill: parent
        source: blueBox
        maskSource: mask
    }
}
相关问题