QML元素 - LinearGradient

QML 的 LinearGradient 用于创建线性渐变效果,适用于背景、形状填充等场景。以下是其使用技巧和关键点:


1. 基本用法

import QtQuick 2.15

Rectangle {
    width: 200
    height: 100

    gradient: LinearGradient {
        start: Qt.point(0, 0)   // 渐变起点 (默认)
        end: Qt.point(width, 0) // 渐变终点 (默认水平向右)

        GradientStop { position: 0.0; color: "red" }
        GradientStop { position: 1.0; color: "blue" }
    }
}
  • start 和 end:定义渐变方向,通过坐标点(如 Qt.point(x, y))设置。
  • GradientStop:定义颜色停靠点,position 范围 0.0 到 1.0color 支持 HEX、RGB 或颜色名称。

2. 控制渐变方向

通过调整 start 和 end 的坐标,实现不同方向的渐变:

  • 水平渐变start: Qt.point(0, 0); end: Qt.point(width, 0)
  • 垂直渐变start: Qt.point(0, 0); end: Qt.point(0, height)
  • 对角渐变start: Qt.point(0, 0); end: Qt.point(width, height)
  • 反向渐变:交换 start 和 end 的坐标。

3. 多颜色渐变

添加多个 GradientStop 实现复杂过渡:

LinearGradient {
    start: Qt.point(0, 0)
    end: Qt.point(0, height)

    GradientStop { position: 0.0; color: "#FF0000" }
    GradientStop { position: 0.5; color: "#00FF00" }
    GradientStop { position: 1.0; color: "#0000FF" }
}

4. 动态渐变

通过绑定属性或动画实现动态渐变效果:

Rectangle {
    id: rect
    width: 200
    height: 200

    property real gradientPos: 0.0

    gradient: LinearGradient {
        start: Qt.point(0, 0)
        end: Qt.point(width, height)

        GradientStop { position: 0.0; color: "yellow" }
        GradientStop { position: rect.gradientPos; color: "green" }
        GradientStop { position: 1.0; color: "purple" }
    }

    NumberAnimation {
        target: rect
        property: "gradientPos"
        from: 0.0
        to: 1.0
        duration: 2000
        loops: Animation.Infinite
        running: true
    }
}

5. 透明渐变

使用带 Alpha 通道的颜色实现透明效果:

GradientStop { position: 0.0; color: "#80FF0000" } // 半透明红色

6. 性能优化

  • 避免频繁更新:动态修改渐变属性可能导致性能下降,尤其在低端设备上。
  • 复用渐变对象:多个元素共享相同的渐变时,定义在外部并通过 id 引用。

7. 常见问题

  • 渐变不显示:检查 start 和 end 是否在元素边界内,或颜色值是否有效。
  • 锯齿感:确保颜色停靠点 (position) 分布均匀,或使用相近颜色平滑过渡。

8. 进阶技巧

  • 与遮罩结合:通过 OpacityMask 实现复杂形状渐变。
  • 文本渐变:对 Text 元素使用 layer.enabled 和 LinearGradient
    Text {
        text: "Gradient Text"
        font.pixelSize: 32
    
        layer.enabled: true
        layer.effect: LinearGradient {
            start: Qt.point(0, 0)
            end: Qt.point(width, 0)
            GradientStop { position: 0.0; color: "red" }
            GradientStop { position: 1.0; color: "blue" }
        }
    }
    

通过灵活组合 start/end 坐标、颜色停靠点和动画,可以轻松实现丰富的视觉效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

“不靠谱”的深度体验派

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值