如何使部分区域透明,其余区域半透明?

How to make part of area transparent and the rest show semitransparent?

我正在尝试在图像中制作一个 select 可用的矩形。

Image {
    id: image
    Rectangle { //full-transparent like a viewport
        id: rect
    }
}

像截图一样,你select的区域是全透明的,其余部分是半透明(或模糊)。

我发现opacitymask有点相似,但我希望其余区域显示半透明,而不仅仅是白色。

本项目完整代码:https://github.com/arkceajin/QtDemos/tree/master/CropBox

对于这些情况,您必须使用 ShaderEffect:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("ShaderEffect Example")

    Image {
        id: image
        source: "qrc:/dog.png"
        anchors.centerIn: parent

        layer.enabled: true
        layer.effect: ShaderEffect {
            property real alpha: 0.4
            property rect sourceRect: Qt.rect(width/4, height/4, width/2, height/2)

            property real xStep: 1/width
            property real yStep: 1/height

            fragmentShader: "
                uniform lowp sampler2D source;
                varying mediump vec2 qt_TexCoord0;
                uniform lowp float qt_Opacity;

                uniform highp float alpha;
                uniform highp vec4 sourceRect;

                uniform highp float xStep;
                uniform highp float yStep;

                bool insideBox(vec2 topLeft, vec2 bottomRight, vec2 point){
                    vec2 s = step(topLeft, point) - step(bottomRight, point);
                    return (s.x * s.y) > 0.0;
                }

                void main() {
                    vec2 topLeft = vec2(sourceRect.x*xStep, sourceRect.y*yStep);
                    vec2 bottomRight = topLeft + vec2(sourceRect.z*xStep, sourceRect.w*yStep);
                    gl_FragColor = texture2D(source, qt_TexCoord0) * qt_Opacity;
                    if(!insideBox(topLeft, bottomRight, qt_TexCoord0))
                        gl_FragColor *= alpha;

                }
            "
        }
    }
}

输出: