-
Notifications
You must be signed in to change notification settings - Fork 4
/
animatedlabel.cpp
73 lines (62 loc) · 1.66 KB
/
animatedlabel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "animatedlabel.h"
#include <QImage>
#include <QtMath>
AnimatedLabel::AnimatedLabel(QWidget *parent) :
QLabel(parent),
currentIndex(0),
_isPlaying(false)
{
// hide when not playing
setVisible(false);
}
void AnimatedLabel::initialize(const QString &imagePath, const int fps, const int startLoopIndex, const int endLoopIndex, const int width, const int height)
{
pixmapSize.setWidth(width);
pixmapSize.setHeight(height);
this->startLoopIndex = startLoopIndex;
this->endLoopIndex = endLoopIndex;
QImage img;
img.load(imagePath);
int count = (img.height() * img.width()) / (width * height);
for (int i = 0; i < count; i++)
{
int x = (i % 5) * pixmapSize.height();
int y = qFloor(i / 5) * pixmapSize.width();
QImage sprite = img.copy(x, y, pixmapSize.width(), pixmapSize.height());
pixmaps.push_back(QPixmap::fromImage(sprite));
}
connect(&timer, &QTimer::timeout, this, &AnimatedLabel::switchPixmap);
timer.setInterval(1000 / fps);
}
void AnimatedLabel::start()
{
currentIndex = 0;
_isPlaying = true;
setVisible(true);
timer.start();
}
void AnimatedLabel::stop()
{
_isPlaying = false;
}
bool AnimatedLabel::isPlaying()
{
return _isPlaying;
}
void AnimatedLabel::switchPixmap()
{
if (_isPlaying)
{
if (endLoopIndex > 0 && currentIndex > endLoopIndex)
currentIndex = startLoopIndex;
else if (currentIndex >= pixmaps.length())
currentIndex = 0;
}
else if (currentIndex >= pixmaps.length())
{
setVisible(false);
timer.stop();
return;
}
setPixmap(pixmaps.at(currentIndex++));
}