2017-05-24 188 views
0

在下面的代碼中,我想使用透明矩形來隱藏圖像。請給我一些解決方案。我已經使用z值,但它不起作用。圖像仍然可見。如何在QML中使用透明矩形隱藏圖像?

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 
    } 
} 
+0

由於矩形是透明的,下面的圖像將被看到。我想你想看看這個領域的形象背後是什麼,但是你最好解釋一下。我認爲這很難實施。 –

+0

實際上我想通過剪切來部分隱藏圖像。 –

+0

您可能想閱讀:https://css-tricks.com/cutting-inner-part-element-using-clip-path/ –

回答

0

可以使用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 
    } 
} 

enter image description here

+0

我無法重現您顯示的效果。 'layer.enabled:true; layer.effect:OpacityMask {maskSource:hiding_rect}'沒有任何作用 –

0

還有另一種方式來使用OpacityMask,和Qt版本應該> = 5.7。

import QtQuick 2.5 
import QtQuick.Controls 1.4 
import QtGraphicalEffects 1.0 

ApplicationWindow { 
    visible: true 
    width: 1280 
    height: 800 
    title: qsTr("Hello World") 

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

    Image 
    { 
     id:underlyingImage 
     width: 1204 
     height: 682 
     visible: false 

     source:"qrc:/timg.jpg" 
    } 
    Item { 
     id: hiding_rect 
     anchors.fill: underlyingImage 
     visible: false 
     Rectangle { 
      width: underlyingImage.width/2 
      height: underlyingImage.height/2 
      color: "yellow" 
     } 
    } 
    OpacityMask { 
     anchors.fill: underlyingImage 
     source: underlyingImage 
     maskSource: hiding_rect 
     invert: true 
    } 
} 

the result picture