QML提供了丰富的动画元素,说起动画,无非是给UI增光添彩罢了。在QML中,动画常常与State和Transition联系在一起,这几个概念(下面的例子中都用到了)都比较简单,相关介绍可查看Qt官方文档,网址如下:
http://doc.qt.io/qt-5/qtquick-statesanimations-topic.html
下面先列举几个QML动画元素,动画效果可“忘文生意”:
PropertyAnimation(常用)
AnchorAnimation
ColorAnimation
NumberAnimation
ParentAnimation
PathAnimation
RotationAnimation
Vector3dAnimation
SequentialAnimation
ParalleAnimation
PauseAnimation
SmoothedAnimation
SpringAnimation
PropertyAction(无动画效果)
ScriptAction
Behavior(设置默认动画)
常见的QML动画有三种表示方式,下面一一说明。
1、使用State和Transition
State改变属性值,Transition实现动画,例子如下:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: rect
width: 100
height: 100
color: "blue"
MouseArea {
anchors.fill: parent
// state属性值为空字符串时('')即默认状态
onClicked: container.state == 'right' ? container.state = '' : container.state = 'right'
}
}
states: State {
name: "right"
// rect水平移动
PropertyChanges {
target: rect
x: 260
}
}
transitions: Transition {
// 数字(x坐标)动画,设置了easing的回弹效果和动画时间
NumberAnimation {
property: "x"
easing.type: Easing.InOutBounce
duration: 500
}
}
}
2、使用Behavior
直接修改上面的例子,实现同样的动画效果,结果如下:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: rect
width: 100
height: 100
color: "blue"
// 看这里
Behavior on x {
NumberAnimation {
easing.type: Easing.InOutBounce
duration: 500
}
}
MouseArea {
anchors.fill: parent
// 改变rect的x坐标
onClicked: rect.x = (rect.x == 0 ? 260 : 0)
}
}
}
3、其它
还是在上面例子的基础上修改以实现同样的效果,代码如下:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: rect
width: 100
height: 100
color: "blue"
// rect水平右移
NumberAnimation on x {
id: right
running: false // false
to: 260
easing.type: Easing.InOutBounce
duration: 500
}
// rect水平左移
NumberAnimation on x {
id: left
running: false // false
to: 0
easing.type: Easing.OutInBounce // 换个easing动画效果
duration: 500
}
MouseArea {
anchors.fill: parent
// 判断移动方向
onClicked: rect.x == 0 ? right.running = true : left.running = true
}
}
}
下面再来看一个有意思的例子,parallel和sequential动画:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: up
width: 100
height: 100
color: "blue"
// 并行动画,水平移动和颜色变化同时进行
ParallelAnimation {
id: parallel
running: false
PropertyAnimation {
target: up
property: "x"
to: 260
duration: 500
}
PropertyAnimation {
target: up
property: "color"
to: "red"
duration: 500
}
}
MouseArea {
anchors.fill: parent
onClicked: parallel.running = true
}
}
Rectangle {
id: down
width: 100
height: 100
color: "red"
anchors.top: up.bottom
// 串行动画,先进行水平移动,后进行颜色变化
SequentialAnimation {
id: sequential
running: false
PropertyAnimation {
target: down
property: "x"
to: 260
duration: 500
}
PropertyAnimation {
target: down
property: "color"
to: "blue"
duration: 500
}
}
MouseArea {
anchors.fill: parent
onClicked: sequential.running = true
}
}
}
关于QML动画,Qt官网文档也做了详细的介绍:
http://doc.qt.io/qt-5/qtquick-usecase-animations.html
http://doc.qt.io/qt-5/qtquick-statesanimations-animations.html