Strange alpha blending results with ShaderEffectItem

余生长醉 提交于 2019-12-21 20:33:16

问题


I'm trying to apply a simple alpha mask on a QML item using ShaderEffectItem.

Here is a minimal (non-)working example: I have a red-to-white gradient as the background and want to draw a green 200x200 square on top of it. The alpha mask for this square should be 0.0 at the left and 1.0 at the right border, so it should be transparent at the left border.

import QtQuick 1.1
import Qt.labs.shaders 1.0

Rectangle {
    width: 300
    height: 300

    id: wrapper

    gradient: Gradient {
        GradientStop { position: 0.0; color: "red" }
        GradientStop { position: 1.0; color: "white" }
    }

    Rectangle {
        id: square
        anchors.centerIn: parent
        width: 200
        height: 200
        color: "green"
    }

    ShaderEffectItem {
        anchors.centerIn: parent
        width: 200
        height: 200

        property variant source: ShaderEffectSource {
            sourceItem: square
            hideSource: true
        }

        fragmentShader: "
        varying vec2 qt_TexCoord0;
        uniform sampler2D source;
        void main(void)
        {
            vec4 sourceColor = texture2D(source, qt_TexCoord0);
            float alpha = qt_TexCoord0.x; // = 0.0 at left, 1.0 at right border
            sourceColor.a *= alpha;       // apply alpha mask
            gl_FragColor = sourceColor;
        }
        "
    }
}

I expected the following output (drawn with GIMP):

But this is actually shown:

What am I doing wrong?

I'm using qmlviewer (Qt 4.8.2) to display the QML file with the -opengl option in order to enable the shader effect.

Maybe this is related to this strange behavior with alpha blending on QGLFramebufferObjects I found some weeks ago...


回答1:


Try modifying the main function of the fragment shader to :

    void main(void)
    {
        gl_FragColor = texture2D(source, qt_TexCoord0).rgba*qt_TexCoord0.x;
    }


来源:https://stackoverflow.com/questions/13161296/strange-alpha-blending-results-with-shadereffectitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!