QML圓形圖像的製作與圖像置灰效果

在用QML開發界面時,往往我們想將一個方形的圖片顯示成圓形,類似於早期QQ的圓形圖像,許多人想到用radius屬性與clip屬性進行嘗試,但是,始終是沒有成功,看來Qt還是沒有強大到一定程度啊,哈哈哈。接下來我就簡單碼上幾句實現圓形圖像的方法,以及將彩色圖像置灰(放QQ離線)的一下方法:
一、將方形圖片圓形顯示
代碼如下:
Rectangle {
        id: img
        width: 100
        height: 100
        radius: width/2
        color: "black"


        Image {
            id: _image
            smooth: true
            visible: false
            anchors.fill: parent
            source: "./testPic.jpg"
            sourceSize: Qt.size(parent.size, parent.size)
            antialiasing: true
        }
        Rectangle {
            id: _mask
            color: "black"
            anchors.fill: parent
            radius: width/2
            visible: false
            antialiasing: true
            smooth: true
        }
        OpacityMask {
            id:mask_image
            anchors.fill: _image
            source: _image
            maskSource: _mask
            visible: true
            antialiasing: true
        }
    }
對沒錯,運行OpacityMask可以實現,其參數source和maskSource官方給的解釋爲:
source : variant
This property defines the source item that is going to be masked.

maskSource : variant
This property defines the item that is going to be used as the mask. The mask item gets rendered into an intermediate pixel buffer and the alpha values from the result are used to determine the source item's pixels visibility in the display.
即通過maskSource對source進行遮擋,顯示的外觀形狀爲maskSource,內容顯示爲source的內容,因爲上例中的maskSource爲Rectangle且radius: width/2,即爲圓形,所以顯示出來的圖片爲圓形。
效果如下:



二、將彩色圖像置灰
以下介紹如何將上例中的圓形圖像編程黑白色(以下代碼中的img爲上例中的最外層Rectangle)。
代碼如下:
Colorize {
        anchors.fill: img
        width: 100
        height: 100
        source: img
        hue: 0.0
        saturation: 0.0
        lightness: 0.0
        visible:false
    }
是的,通過設置Colorize的色調屬性hue、飽和度屬性saturation和亮度屬性lightness,可以將一個彩色的圖片顯示成灰色(黑白色),具體各值的變化所代表的意思,請參見Qt的幫助,查詢關鍵字Colorize即可找到。
效果如下:

如果想讓離線效果更明顯一點,可以將lightness: 0.8即亮度設爲0.8,可達到更好的效果,如下:

通過以上幾個QML控件的組合,可以製作出很多的效果,有興趣的可以繼續參與Qt的幫助進行查閱學習。

也希望有興趣的朋友可以和我進行交流學習,關注我的公衆號,搜索【三個程序員】進行關注 ^-^


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章