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.0
,color
支持 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
坐标、颜色停靠点和动画,可以轻松实现丰富的视觉效果。