# 给形状添加动画
使用Qt Quick Shapes的好处之一是绘制的路径直接在QML中定义。 这意味着它们的属性可以被绑定、转换和动画,就像QML中的任何其他属性一样。
在下面的例子中,重用了本章第一部分的基本形状,但引入了一个变量t
,在循环中从0.0
到1.0
设置动画。 然后使用这个变量来偏移小圆圈的位置,以及顶部和底部圆圈的大小。 这将创建一个动画,在该动画中,圆圈似乎出现在顶部并向底部消失。
import QtQuick
import QtQuick.Shapes
Rectangle {
id: root
width: 600
height: 600
Shape {
anchors.centerIn: parent
ShapePath {
id: shapepath
property real t: 0.0
NumberAnimation on t { from: 0.0; to: 1.0; duration: 500; loops: Animation.Infinite; running: true }
strokeWidth: 3
strokeColor: "darkGray"
fillColor: "lightGray"
startX: -40; startY: 200
// The circle
PathArc { x: 40; y: 200; radiusX: 200; radiusY: 200; useLargeArc: true }
PathLine { x: 40; y: 120 }
PathArc { x: -40; y: 120; radiusX: 120; radiusY: 120; useLargeArc: true; direction: PathArc.Counterclockwise }
PathLine { x: -40; y: 200 }
// The dots
PathMove { x: -20+(1.0-shapepath.t)*20; y: 80 + shapepath.t*50 }
PathArc { x: 20-(1.0-shapepath.t)*20; y: 80 + shapepath.t*50; radiusX: 20*shapepath.t; radiusY: 20*shapepath.t; useLargeArc: true }
PathArc { x: -20+(1.0-shapepath.t)*20; y: 80 + shapepath.t*50; radiusX: 20*shapepath.t; radiusY: 20*shapepath.t; useLargeArc: true }
PathMove { x: -20; y: 130 + shapepath.t*50 }
PathArc { x: 20; y: 130 + shapepath.t*50; radiusX: 20; radiusY: 20; useLargeArc: true }
PathArc { x: -20; y: 130 + shapepath.t*50; radiusX: 20; radiusY: 20; useLargeArc: true }
PathMove { x: -20; y: 180 + shapepath.t*50 }
PathArc { x: 20; y: 180 + shapepath.t*50; radiusX: 20; radiusY: 20; useLargeArc: true }
PathArc { x: -20; y: 180 + shapepath.t*50; radiusX: 20; radiusY: 20; useLargeArc: true }
PathMove { x: -20+shapepath.t*20; y: 230 + shapepath.t*50 }
PathArc { x: 20-shapepath.t*20; y: 230 + shapepath.t*50; radiusX: 20*(1.0-shapepath.t); radiusY: 20*(1.0-shapepath.t); useLargeArc: true }
PathArc { x: -20+shapepath.t*20; y: 230 + shapepath.t*50; radiusX: 20*(1.0-shapepath.t); radiusY: 20*(1.0-shapepath.t); useLargeArc: true }
}
}
}
请注意,不仅仅在t
上可以使用NumberAnimation
,而是可以使用任何其他绑定,例如:绑定到滑块、外部状态等。 只要能想到,都能实现。