下面這個程式很簡單,示範如何使用QCanvasSprite進行動畫播放,畫面會有兩隻小毛蟲進行賽跑,不斷的一伸一縮並向右移動:
在QCanvasSprite的精神就是設定一個物件,它的顯示圖片可以變化~
這一個例子就是兩個圖片一直循環變化~
因為QCanvasSprite是繼承QCanvasItem,所以,呼叫void QCanvasItem::setVelocity ( double vx, double vy ) [virtual],可以設定它的移動速度~
main.cpp
#include <qapplication.h>
#include <qcanvas.h>
#include <qimage.h>
class Caterpillar : public QCanvasSprite {
public:
Caterpillar(QCanvas *canvas) : QCanvasSprite(0, canvas) {
static QCanvasPixmapArray ani;
ani.setImage(0, new QCanvasPixmap("cater1.jpg")); // 讀入一組圖片
ani.setImage(1, new QCanvasPixmap("cater2.jpg"));
setSequence(&ani); // setup圖片組
setFrameAnimation(QCanvasSprite::Cycle); // 循環播放
}
};
class View : public QCanvasView {
public:
View(QCanvas& canvas) : QCanvasView(&canvas){
canvas.resize(300, 200);
setFixedSize(sizeHint());
Caterpillar *cater1 = new Caterpillar(&canvas);
cater1->move(250, 50);
cater1->setVelocity(-1, 0);
cater1->setZ(10);
cater1->show();
Caterpillar *cater2 = new Caterpillar(&canvas);
cater2->move(250, 100);
cater2->setVelocity(-1.5, 0);
cater2->setZ(10);
cater2->show();
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
QCanvas canvas(0, 0);
canvas.setAdvancePeriod(500); // 移動更新間隔,同時,每500ms會變換圖片一次
canvas.setDoubleBuffering(true); // double buffer
View c(canvas);
app.setMainWidget(&c);
c.show();
return app.exec();
}
參考資料:
QCanvas 類別 - QCanvasSprite 動畫播放
沒有留言:
張貼留言