2016-08-17 79 views
1
邊境

這個問題我有似乎是很常見的其他語言和框架:梯度上的一個矩形在QML

如何申請一個矩形邊框漸變? 我的解決方案至今是一個自定義組件,例如:

Item { 
    id: root 
    property int borderWidth 
    property alias borderGradient: border.gradient 
    property alias gradient: fill.gradient 
    property alias color: fill.color 
    property int radius 

    Rectangle { 
     id: border 
     anchors.fill: parent 
     radius: root.radius 

     Rectangle { 
      id: fill 
      anchors.fill: parent 
      anchors.margins: root.borderWidth 
      radius: root.radius * width/border.width/2 
     } 
    } 
} 

然而,這並不讓我,設置矩形的顏色爲「透明」,這是可悲的,但我可以忍受。不過我想,如果有可能是一個更優雅的方式(除了使用Context2D或直接在QSG ...)

問候,
-M-

+1

'QQuickPaintedItem'可能是最簡單的。可能有一些方法使用'OpacityMask'着色器效果來破解它,或者在'Canvas'中畫一次梯度框架,然後使用畫布作爲圖像源,類似於此處所述的方法:http://stackoverflow.com/questions/35025386/using-arbitrary-qml-items-as-cached-image-source – dtech

+0

哇,看起來很複雜。我需要相當一段時間來消化這個。謝謝! – derM

+0

儘管我儘量避免使用QtGraphicalEffects,但OpacityMask確實非常強大! – derM

回答

0

繼ddriver從意見的建議,我把一起使用矩形的一個工作樣本,您可以使用OpacityMask爲邊框設置漸變。 聽說某個地方,該QtGraphicalEffects有糟糕的表現,所以我可能會嘗試一個沒有,在未來,但對任何人說不用擔心,這是一個工作示例:

import QtQuick 2.0 
import QtGraphicalEffects 1.0 

Rectangle { 
    id: root 
    property Gradient borderGradient 
    property int borderWidth: 0 


    Loader { 
     id: loader 
     active: borderGradient 
     anchors.fill: parent 
     sourceComponent: border 
    } 

    Component.onCompleted: console.log(loader.active) 

    Component { 
     id: border 
     Item { 
      Rectangle { 
       id: borderFill 
       radius: root.radius 
       anchors.fill: parent 
       gradient: root.borderGradient 
       visible: false 
      } 

      Rectangle { 
       id: mask 
       radius: root.radius 
       border.width: root.borderWidth 
       anchors.fill: parent 
       color: 'transparent' 
       visible: false // otherwise a thin border might be seen. 
      } 

      OpacityMask { 
       id: opM 
       anchors.fill: parent 
       source: borderFill 
       maskSource: mask 
      } 
     } 
    } 
} 

它只會使用OpacityMask當需要時(當設置borderGradient時),否則它的行爲就像一個普通的矩形。

我希望我可以幫助這個人。