qml实现一个好看的水波纹
时间: 2023-11-05 22:11:55 浏览: 147
好的,下面是一个简单的 QML 实现水波纹效果的示例代码:
```qml
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtGraphicalEffects 1.0
Rectangle {
width: 200
height: 200
color: "#333"
MouseArea {
anchors.fill: parent
hoverEnabled: true
onPositionChanged: {
waterRipple.x = mouse.x - waterRipple.width / 2
waterRipple.y = mouse.y - waterRipple.height / 2
waterRipple.visible = true
}
onExited: {
waterRipple.visible = false
}
}
Item {
id: waterRipple
visible: false
x: -50
y: -50
width: 100
height: 100
Image {
anchors.fill: parent
source: "qrc:/ripple.png"
fillMode: Image.PreserveAspectFit
SequentialAnimation {
id: rippleAnimation
running: false
loops: 1
PropertyAnimation {
target: waterRipple
property: "scale"
to: 2
duration: 500
}
PropertyAnimation {
target: waterRipple
property: "opacity"
to: 0
duration: 500
}
onStopped: {
waterRipple.scale = 1
waterRipple.opacity = 1
waterRipple.visible = false
}
}
ShaderEffect {
property variant source: rippleImage
property variant resolution: Qt.size(width, height)
property real amplitude: 0.1
property real speed: 0.001
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 * qt_Opacity;
}
"
}
}
}
}
```
该示例代码中,我们使用了一个 `MouseArea` 来捕获鼠标移动事件,当鼠标移动到 `Rectangle` 区域内时,会在鼠标位置显示一个水波纹效果。水波纹效果的容器是一个 `Item`,其中包含了一个 `Image` 和一个 `ShaderEffect`。`Image` 中使用了一个波形图片作为水波纹的纹理。`ShaderEffect` 中使用了 GLSL 代码来实现水波纹的动画效果。具体实现方式是在纹理坐标上加上一个偏移量,偏移量的大小和方向由时间和振幅决定,时间和振幅的值会随着动画的进行而改变。
请将示例代码保存到 `main.qml` 文件中,并将波形图片保存到 `ripple.png` 文件中,放在相同的目录下。运行程序后,鼠标在 `Rectangle` 区域内移动时,会出现一个水波纹效果。
阅读全文