如何使用Qt Quick制作圆形头像

<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()

结果

0_1470144427736_result1.png

优点

代码 简洁通俗易懂

缺点

如结果所示。颗粒 现象非常严重

<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覆盖源覆盖形状 进行处理

结果

0_1470145364888_result2.png

优点

使用 Qt 自带的功能,保证了质量
图片效果 较好

缺点

占用资源 猜测

欢迎补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值