【问题标题】:How to hide an image using transparent rectangle in QML?如何在 QML 中使用透明矩形隐藏图像?
【发布时间】:2017-05-24 18:07:42
【问题描述】:

在下面的代码中,我想使用透明矩形隐藏图像。请给我一些解决方案。我使用了 z 值,但它不起作用。图像仍然可见。

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Image
    {
        id:underlyingImage
        width: 400
        height: 400
        x:0;
        y:0;
        source:"qrc:/Jellyfish.jpg"
        z:1
    }
    Rectangle
    {
        id:hiding_rect
        width: 400
        height: 400
        x:0;
        y:0;
        color:"transparent"
        z:100
    }
}

【问题讨论】:

  • 由于矩形是透明的,所以会看到下图。我想你想看看这个区域的图像背后是什么,但你最好解释一下。我认为这很难实现。
  • 其实我想通过剪裁部分隐藏图像。

标签: qt qml qt-quick


【解决方案1】:

您可以使用 OpacityMask 来实现您所尝试的,在下面的示例中,我们隐藏了图像的一个象限。

import QtQuick 2.5
import QtQuick.Window 2.2
import QtGraphicalEffects 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Image
    {
        id:underlyingImage
        width: 400
        height: 400

        fillMode: Image.PreserveAspectCrop
        layer.enabled: true
        layer.effect: OpacityMask {
            maskSource: hiding_rect
        }

        source:"qrc:/Jellyfish.jpg"
    }
    Rectangle
    {
        id:hiding_rect
        width: underlyingImage.width/2
        height: underlyingImage.height/2
    }
}

【讨论】:

  • 我无法重现您显示的效果。 layer.enabled: true; layer.effect: OpacityMask { maskSource: hiding_rect } 没有任何作用
【解决方案2】:

还有另一种使用OpacityMask的方法,但你的Qt版本应该>= 5.7。

import QtQuick 2.0
import QtQuick.Window 2.0
import QtGraphicalEffects 1.0

Window {
    width: 1280
    height: 800
    visible: true

    Rectangle {
        id: background
        anchors.fill: parent
        color: "black"
    }

    Image {
        id: underlyingImage
        width: 1204
        height: 682
        visible: false
        source: "qrc:/timg.jpg"
    }

    Item {
        id: hidingRect
        anchors.fill: underlyingImage
        visible: false

        Rectangle {
            width: underlyingImage.width / 2
            height: underlyingImage.height / 2
            color: "yellow"
        }
    }

    OpacityMask {
        anchors.fill: underlyingImage
        source: underlyingImage
        maskSource: hidingRect
        invert: true
    }
}

The result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2014-12-01
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多