QML不仅可以显示静态图像,而且支持GIF格式动态图像显示,还可实现图像在三维空间的立体旋转功能。
本文实例实现GIF图像的立体旋转,运行效果如下图所示,卡通飞机在天空飞翔,同时整个图像沿竖直轴缓慢地转动。
实现步骤如下。
(1) 新建项目
新建QML应用程序,项目名称为“Graph3DRotate”。
(2)准备图片
在项目工程目录中建一个images文件夹,其中放入一幅图像“plane.gif”。右击项目视图“Resources”一“qml.qrc”下的“/”节点,选择“Add Existing...”项,从弹出的对话框中选择该图像并打开,将其加载到项目中。
(3)自定义元素
右击项目视图“Resources”—“qml.qrc”下的“/”节点,选择“Add New...”项,新建“MyGraph.qml”文件,编写代码如下:
import QtQuick 2.0
Rectangle { //矩形作为图像显示区
/*矩形宽度、高度皆与图像尺寸吻合*/
width: animg.width
height: animg.height
transform: Rotation {// (a)
/*设置图像原点*/
origin.x: animg.width/2
origin.y: animg.height/2
axis {
x: 0
y: 1//绕y轴转动
z: 0
}
NumberAnimation on angle {//定义角度angle上的动画
from: 0
to: 360
duration: 5000
loops: Animation.Infinite
}
}
AnimatedImage { //(b)
id: animg
source : "images/plane.gif" //图像路径
scale: 0.5
}
}
其中,
- (a) transform: Rotation {…}: transform属性,需要指定一个Transform类型元素的列表。在QML中可用的Transform类型有3个:Rotation、Scale和Translate,分别用来进行旋转、缩放和平移。这些元素还可以通过专门的属性来进行更加高级的变换设置。其中,Rotation提供了坐标轴和原点属性,坐标轴有axis.x、axis.y和axis.z,分别代表x轴、y轴和z轴,因此可以实现3D效果。原点由origin.x和origin.y来指定。对于典型的3D旋转,既要指定原点,也要指定坐标轴。下图为旋转坐标示意图,使用angle属性指定顺时针旋转的角度。
- (b) AnimatedImage {…}: AnimatedImage扩展了Image元素的功能,可以用来播放包含一系列帧的图像动画,如GIF文件。当前帧和动画总长度等信息可以使用currentFrame和frameCount属性来获取,还可以通过改变playing和paused属性的值来开始、暂停和停止动画。
(4)主程序
打开“main.qml”文件,编写代码如下:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
width: 400
height: 300
visible: true
title: qsTr("Graph3DRotate")
Rectangle {
width: 360
height: 360
anchors.fill: parent
MyGraph { // 使用组件
anchors.centerIn: parent
}
}
}
————————————————
觉得有用的话请关注点赞,谢谢您的支持!
对于本系列文章相关示例完整代码有需要的朋友,可关注并在评论区留言!