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

294 Views Asked by At

I am trying to make a selectable rectangle inside an image.

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

which looks like using the screenshot, the area which you select is full-transparent, but the rest is semi-transparent(or blur).

enter image description here

I found opacitymask which is a little bit similar, but I want the rest of the area shows semi-transparent, not just white.

The complete code of this project: https://github.com/arkceajin/QtDemos/tree/master/CropBox

1

There are 1 best solutions below

3
eyllanesc On BEST ANSWER

For these cases you must use 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;

                }
            "
        }
    }
}

Output:

enter image description here