QML —— 遮罩功能,模拟软件头像功能(附源码)
效果
说明
该遮罩功能使用了组件,Component 是Qt 框架或者开发者封装好的、只暴露必要接口的QML 类型,可以重复使用。要再QML 中嵌入Component 的定义,需要使用Component 对象。
代码
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.14
Window
{
visible: true
width: 900
height: 420
ColumnLayout
{
anchors.centerIn: parent
Text {text: qsTr("原图:");font.pixelSize: 20;color: "green"}
RowLayout
{
spacing: 40
IconComponent{id: srcImage1; width: 100;height: 100;}
IconComponent{id: srcImage2; width: 100;height: 100;}
IconComponent{id: srcImage3; width: 100;height: 100;}
IconComponent{id: srcImage4; width: 100;height: 100;}
IconComponent{id: srcImage5; width: 100;height: 100;}
IconComponent{id: srcImage6; width: 100;height: 100;}
}
Rectangle{height: 50}
Text {text: qsTr("遮罩:");font.pixelSize: 20;color: "green"}
RowLayout
{
spacing: 40
IconComponent{id: maskImage1; width: 100;height: 100;}
IconComponent{id: maskImage2; width: 100;height: 100;}
IconComponent{id: maskImage3; width: 100;height: 100;}
IconComponent{id: maskImage4; width: 100;height: 100;}
IconComponent{id: maskImage5; width: 100;height: 100;}
IconComponent{id: maskImage6; width: 100;height: 100;}
}
}
Component.onCompleted:
{
srcImage1.setSourceImage("qrc:/image/image/1.png")
srcImage2.setSourceImage("qrc:/image/image/2.jpg")
srcImage3.setSourceImage("qrc:/image/image/3.jpg")
srcImage4.setSourceImage("qrc:/image/image/4.jpg")
srcImage5.setSourceImage("qrc:/image/image/5.jpg")
srcImage6.setSourceImage("qrc:/image/image/6.jpg")
maskImage1.setSourceImageMask("qrc:/image/image/1.png")
maskImage2.setSourceImageMask("qrc:/image/image/2.jpg")
maskImage3.setSourceImageMask("qrc:/image/image/3.jpg")
maskImage4.setSourceImageMask("qrc:/image/image/4.jpg")
maskImage5.setSourceImageMask("qrc:/image/image/5.jpg")
maskImage6.setSourceImageMask("qrc:/image/image/6.jpg")
}
}
IconComponent.qml
import QtQuick 2.0
import QtGraphicalEffects 1.14
Item
{
Image
{
id: sourceimage
sourceSize: Qt.size(parent.width,parent.height)
smooth: true
visible: false
}
Rectangle
{
id: mask
width: parent.width
height: parent.height
radius: height/2
color: "red"
visible: false
}
OpacityMask
{
source: sourceimage
anchors.fill: sourceimage
maskSource: mask
}
// 显示原图
function setSourceImage(imagePath)
{
sourceimage.source = imagePath
sourceimage.visible= true
}
// 显示遮罩效果
function setSourceImageMask(imagePath)
{
sourceimage.source = imagePath
}
}
关注
笔者 - jxd