下面的 QML 代码为两个矩形设置动画。一个使用PropertyAnimation,而另一个使用NumberAnimation。两个矩形的移动方式相似。我看不出这两种动画类型有什么不同。
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
visible: true
width: 640
height: 480
Rectangle {
id: r1
width: 100; height: 100
color: "red"
Behavior on x { PropertyAnimation {} }
}
Rectangle {
id: r2
y: 150
width: 100; height: 100
color: "blue"
Behavior on x { NumberAnimation {} }
}
// click anywhere to start animation
MouseArea { anchors.fill: parent; onClicked: r1.x = r2.x = 200 }
}
Run Code Online (Sandbox Code Playgroud)
是有什么区别PropertyAnimation和NumberAnimation; 我什么时候应该使用一个?
NumberAnimation是衍生自PropertyAnimation,因此,它使逻辑意义为它们表现出类似的行为。
NumberAnimation 是一个专门的 PropertyAnimation,它定义了当数值改变时要应用的动画。 (来源)
虽然NumberAnimation 专门为数字值(例如x、y、width、opacity)设置动画,但它PropertyAnimation是通用的并且可以为非数字值设置动画(例如color、size)。
乐长回答:
PropertyAnimation可以为非数字类型设置动画。NumberAnimation只动画数字。NumericAnimation可以动画数字属性,例如 x、y、宽度、高度、不透明度。但它不能为 color、size或points设置动画。
这是一个示例,其中动画类型在为color属性设置动画时有所不同。第一个矩形从红色变为绿色,而第二个矩形保持蓝色。在这种情况下,PropertyAnimation应该使用 over NumberAnimation。
Rectangle {
id: r1
width: 100; height: 100
color: "red"
Behavior on color { PropertyAnimation {} } // works
}
Rectangle {
id: r2
y: 150
width: 100; height: 100
color: "blue"
Behavior on color { NumberAnimation {} } // fails
}
MouseArea { anchors.fill: parent; onClicked: r1.color = r2.color = "green" }
Run Code Online (Sandbox Code Playgroud)
但话又说回来,你可以ColorAnimation改为......
PropertyAnimation是通用的。这是从#1的构建。但这本身就是另一个优势。
由于PropertyAnimation更通用,如果您决定使用动态PropertyAnimation::property.
下面是一个动画属性由用户提供的示例:
Rectangle {
id: rect
width: 100; height: 100
color: "red"
PropertyAnimation { id: animation; target: rect }
}
MouseArea {
anchors.fill: parent
onClicked: {
animation.property = t1.text;
animation.to = t2.text;
animation.start();
}
}
Row {
width: parent.width; height: 50
anchors.bottom: parent.bottom
TextField { id: t1; width: parent.width/2; height: 50; placeholderText: "property" }
TextField { id: t2; width: parent.width/2; height: 50; placeholderText: "to" }
}
Run Code Online (Sandbox Code Playgroud)
使用NumberAnimation也有效,但将可行属性限制为仅数字属性...用户无法模拟超新星或彩虹。:(
NumberAnimation严格。让我们比较from和to属性。
NumberAnimation
from: realto: realPropertyAnimation
from: variantto: variant这使得NumberAnimation更严格。QML 会防止你犯愚蠢的错误:
NumberAnimation {
id: animation
to: "green" // Invalid property assignment: number expected
}
Run Code Online (Sandbox Code Playgroud)
当您严格限制动画数字时使用它。
这也意味着使用NumberAnimation可以提高可读性和交流。它告诉阅读你的代码的人你只是想为数字设置动画——而不是锚点、颜色、独角兽或其他任何东西。
NumberAnimation更有效地为数字设置动画。– Qt 说:
专用属性动画类型比 PropertyAnimation 类型具有更高效的实现。 (来源)
此处,“专用类型”是指NumberAnimation,以及其他类型,例如AnchorAnimation和ColorAnimation。
我还没有尝试分析 QML 来对差异进行基准测试,但似乎选择动画类型的经验法则是:
NumberAnimation.PropertyAnimation应该是最后的手段(首选其他类型)。