QML 的 RadialGradient
用于创建径向渐变(从中心向外扩散的渐变效果),适合实现圆形光晕、球体效果或动态背景。以下是其使用技巧和关键点:
1. 基本用法
import QtQuick 2.15
Rectangle {
width: 200
height: 200
gradient: RadialGradient {
center: Qt.point(width/2, height/2) // 渐变中心
radius: Math.min(width, height)/2 // 渐变半径
focal: Qt.point(width/2, height/2) // 焦点位置(默认与 center 重合)
GradientStop { position: 0.0; color: "red" } // 中心颜色
GradientStop { position: 1.0; color: "blue" } // 边缘颜色
}
}
center
:渐变的中心点坐标。radius
:渐变的半径,控制渐变范围。focal
:渐变的焦点位置(起始点),默认与center
重合(同心圆渐变)。GradientStop
:颜色停靠点,position: 0.0
对应焦点位置,1.0
对应边缘。
2. 控制渐变形状
通过调整 center
、radius
和 focal
实现不同效果:
(1) 同心圆渐变
RadialGradient {
center: Qt.point(100, 100)
radius: 100
focal: Qt.point(100, 100) // 焦点与中心重合
// 颜色从中心向外扩散
}
(2) 偏移焦点(光晕效果)
焦点偏离中心时,形成类似聚光灯效果:
RadialGradient {
center: Qt.point(100, 100)
radius: 150
focal: Qt.point(80, 80) // 焦点偏移
GradientStop { position: 0.0; color: "white" }
GradientStop { position: 1.0; color: "transparent" }
}
(3) 椭圆渐变
通过设置非正方形区域实现椭圆渐变:
Rectangle {
width: 300
height: 150
gradient: RadialGradient {
center: Qt.point(150, 75)
radius: 150 // 半径与宽度匹配
// 渐变会拉伸为椭圆形
}
}
3. 多颜色渐变
添加多个 GradientStop
实现复杂颜色过渡:
RadialGradient {
center: Qt.point(100, 100)
radius: 100
GradientStop { position: 0.0; color: "#FF0000" }
GradientStop { position: 0.5; color: "#00FF00" } // 中间绿色
GradientStop { position: 1.0; color: "#0000FF" }
}
4. 动态渐变
结合属性绑定或动画实现动态效果:
Rectangle {
id: root
width: 200
height: 200
property real offset: 0
gradient: RadialGradient {
center: Qt.point(100, 100)
radius: 100
focal: Qt.point(100 + root.offset, 100) // 焦点水平移动
GradientStop { position: 0.0; color: "yellow" }
GradientStop { position: 1.0; color: "purple" }
}
NumberAnimation {
target: root
property: "offset"
from: -50
to: 50
duration: 1000
loops: Animation.Infinite
running: true
}
}
5. 透明渐变
通过 Alpha 通道实现透明过渡:
RadialGradient {
GradientStop { position: 0.0; color: "#80FF0000" } // 半透明红色
GradientStop { position: 1.0; color: "#00000000" } // 完全透明
}
6. 性能优化
- 避免频繁更新:动态修改
radius
或focal
可能影响性能。 - 复用渐变对象:多个元素共享渐变时,定义在外部并通过
id
引用。
7. 常见问题
- 渐变不显示:检查
radius
是否为 0,或focal
是否超出元素边界。 - 颜色分布不均匀:调整
GradientStop
的position
值(例如从0.0
到0.8
留出空白区域)。
8. 进阶技巧
(1) 与遮罩结合
通过 OpacityMask
实现形状裁剪:
Rectangle {
width: 200
height: 200
layer.enabled: true
layer.effect: OpacityMask {
maskSource: Rectangle { // 定义遮罩形状(如圆形)
width: 200
height: 200
radius: 100
}
}
gradient: RadialGradient { /* ... */ }
}
(2) 文字径向渐变
Text {
text: "Radial Text"
font.pixelSize: 32
layer.enabled: true
layer.effect: RadialGradient {
center: Qt.point(width/2, height/2)
radius: Math.min(width, height)/2
GradientStop { position: 0.0; color: "red" }
GradientStop { position: 1.0; color: "blue" }
}
}
总结
RadialGradient
的核心属性是center
、radius
和focal
,通过调整它们可以控制渐变形状。- 适合实现球体、光晕、聚光灯等视觉效果。
- 结合动画或动态属性绑定,可以创建更生动的交互效果。