公众号:Qt那些事儿
序
有一天在吹逼群里,发现一个群里大佬在Steam上上架了一个游戏-秘封旅行 ~Secret Sealing Travel。
这是一个桌宠游戏。
目前采用C#编写,所以目前应该是不跨平台的。他也是C#新手,所以宠物的动画也只是一个单纯的时间戳轮训。自己自定义timer来实现动画效果。我说你可以用Qt的来实现下,大概十几行核心代码就能搞定。
所以这也是我写这篇文章的一个缘由。
代码 QPropertyAnimation
由于资源文件是png,所以这个核心代码就是三张图来回循环。
当然你可以使用QTimer定时器来搞定这件事儿,但是今天要用QPropertyAnimation
本质上就是循环渲染三张图。
直接上代码
首先窗口无边框,要透明
setAttribute(Qt::WA_TranslucentBackground, true);
setWindowFlags(Qt::FramelessWindowHint);
然后声明动画类
m_pAnimation = new QPropertyAnimation(this, "index"); //声明变量跟循环的函数 index
m_pAnimation->setDuration(1000); //一秒循环一次
m_pAnimation->setLoopCount(-1); // 无线循环
m_pAnimation->setStartValue(0); //起始index
m_pAnimation->setEndValue(3); // 结束index
每次都重新设置index
void MainWindow::setIndex(int index)
{
m_pixIndex = index;
update();
}
int MainWindow::getIndex()
{
return m_pixIndex;
}
将资源文件塞到一个list里,每次都渲染一张图片
m_imgList.push_back(QImage(":/res/1.png"));
m_imgList.push_back(QImage(":/res/2.png"));
m_imgList.push_back(QImage(":/res/3.png"));
void MainWindow::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.drawImage(rect(), m_imgList.at(getIndex()));
}
最后上一个最终效果图
视频上传不了,还是看公众号的文章吧
小结
花了不到五分钟写完了,还跨平台。
使用MSVC19编译出来Debug内存占用8M。 Qt真香。
如果使用QOpenGLWidget的话还可以以后走硬件加速。换成qml的话估计会更快吧。
代码在这里
https://github.com/CryFeiFei/Qt_Teach/tree/master/Animation