<1>
使用 canvas 进行绘制
代码
Canvas{
id: imgcanvas
property url src: "qrc:/Images/testtx.png"
property int size: 80
property int borderSize: 1
width: size
height: size
anchors.centerIn: parent
antialiasing: true
Image {
id: img
source: src
visible: false
sourceSize.width: size
sourceSize.height: size
}
onPaint: {
var ctx = getContext("2d");
ctx.lineWidth = 1;
ctx.strokeStyle = "#ecf0f1";
ctx.beginPath();
ctx.arc(size / 2,size / 2, size / 2,0, Math.PI * 2,true);
ctx.clip();
ctx.closePath();
ctx.drawImage(img,0,0,size,size);
ctx.stroke();
}
Component.onCompleted: loadImage(src)
原理
- 先 创建 Canvas
- 然后 设置 锚
- 然后 在 Component.onCompleted 中 载入图像 ->
loadImage(src)
- 然后 在 onImageLoaded 中 重绘 ->
requestPaint()
- 然后 开始绘制路径 ->
ctx.beginPath()
- 然后 使用
arc()
进行 绘制圆 - 然后 调用
clip()
进行 剪裁 - 在之后 结束绘制路径 ->
ctx.closePath()
- 然后 调用绘制函数 ->
ctx.drawImage()
结果
优点
代码 简洁,通俗易懂
缺点
如结果所示。颗粒 现象非常严重
<2>
使用 OpacityMask
代码
Rectangle{
id: rectsrc
color: "#fffffffff"
border.width: borderSize
border.color: "#3498db"
width: size
height: size
radius: size
visible: false
smooth: true
}
Image {
id: image
source: src
sourceSize.width: size
sourceSize.height: size
visible: false
smooth: true
}
OpacityMask{
source: image
maskSource: rectsrc
width: size
height: size
anchors.centerIn: parent
}
原理
- 使用
Rectangle
作为 覆盖形状 - 使用
Image
作为 覆盖源 - 使用
OpacityMask
对 覆盖源 与 覆盖形状 进行处理
结果
优点
使用 Qt 自带的功能,保证了质量
图片效果 较好
缺点
占用资源 (猜测)