qml实现一个好看的水波纹球
时间: 2023-11-05 15:11:55 浏览: 165
下面是一个简单的 QML 实现水波纹球效果的示例代码:
```qml
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtGraphicalEffects 1.0
Item {
property real radius: 100
property real amplitude: 0.1
property real speed: 0.001
property color color: "white"
width: radius*2
height: radius*2
Image {
anchors.fill: parent
source: "qrc:/ripple.png"
fillMode: Image.PreserveAspectFit
SequentialAnimation {
id: rippleAnimation
running: false
loops: Animation.Infinite
PropertyAnimation {
target: waterRipple
property: "scale"
to: 2
duration: 1000
easing.type: Easing.InQuad
}
PropertyAnimation {
target: waterRipple
property: "opacity"
to: 0
duration: 1000
easing.type: Easing.InQuad
}
}
}
ShaderEffect {
id: waterRipple
anchors.fill: parent
visible: false
property variant source: rippleImage
property real amplitude: root.amplitude
property real speed: root.speed
property color color: root.color
fragmentShader: "
varying highp vec2 qt_TexCoord0;
uniform highp float qt_Opacity;
uniform highp float amplitude;
uniform highp float speed;
uniform highp vec2 resolution;
uniform sampler2D source;
void main() {
highp vec2 p = -1.0 + 2.0 * qt_TexCoord0;
highp vec2 uv = qt_TexCoord0;
highp float freq = 10.0;
highp float amp = amplitude / freq;
highp float time = mod(qt_TexCoord0.y + qt_TexCoord0.x + qt_Opacity * speed * 1000.0, freq);
highp vec2 offset = vec2(amp * sin(time * 3.14159 * 2.0), amp * cos(time * 3.14159 * 2.0));
highp vec2 coord = uv + offset;
highp vec4 pixel = texture2D(source, coord);
gl_FragColor = pixel * vec4(color.rgb, qt_Opacity);
}
"
}
MouseArea {
anchors.fill: parent
onPressed: {
waterRipple.visible = true
rippleAnimation.start()
}
onReleased: {
waterRipple.visible = false
rippleAnimation.stop()
}
}
}
```
该示例代码中,我们使用了一个 `Image` 和一个 `ShaderEffect` 来实现水波纹球的效果。将水波纹球作为一个 `Item` 来实现,通过 `radius` 属性指定半径大小。`Image` 中使用了一个波形图片作为水波纹的纹理。`ShaderEffect` 中使用了 GLSL 代码来实现水波纹的动画效果。具体实现方式和前面的示例相似,不同的是这里使用了 `color` 属性来指定水波纹的颜色。
为了实现点击水波纹球时出现水波纹效果,我们在 `MouseArea` 中监听 `onPressed` 和 `onReleased` 事件,并控制 `waterRipple` 的可见性和 `rippleAnimation` 的运行状态。
请将示例代码保存到 `main.qml` 文件中,并将波形图片保存到 `ripple.png` 文件中,放在相同的目录下。运行程序后,点击水波纹球时,会出现一个水波纹效果。
阅读全文