pavelkolodin
pavelkolodin

Reputation: 2967

Fastest code changing pixels in Qt for animation

I want to animate small (100x20) image by changing the color of its pixels by the same value. For example, increase red-channel value by 1 every frame and then decrease back. The image has alpha channel, the animation speed is 30...100 fps (platform dependent; 30 is enough for linux, but windows requires ~70 to look smooth).

As i know, drawing is faster when done in QImage, but displaying is faster with QPixmap.

Upvotes: 1

Views: 1056

Answers (1)

phyatt
phyatt

Reputation: 19112

I like QGraphicsEffects, and QPropertyAnimations. White doesn't colorize, but black does.

#include <QLabel>
#include <QPixmap>
#include <QGraphicsColorizeEffect>
#include <QTimerEvent>
#include <QPropertyAnimation>
#include <QShowEvent>
#include <QDebug>

class Widget : public QLabel
{
    Q_OBJECT
    Q_PROPERTY(qreal redness READ getRedness WRITE setRedness)

public:
    Widget(QWidget *parent = 0)
    {
        QPixmap p(300, 300);
        p.fill(Qt::black);
        this->setPixmap(p);
        colorize = new QGraphicsColorizeEffect();
        colorize->setColor(Qt::red);
        redness = 0;
        colorize->setStrength(redness);
        this->setGraphicsEffect(colorize);

        animation = new QPropertyAnimation(this,"redness");
        animation->setDuration(2000);
        animation->setLoopCount(10);
        animation->setStartValue(0.0);
        animation->setEndValue(1.0);
        animation->setEasingCurve(QEasingCurve::CosineCurve);
        animation->start();
    }

    ~Widget(){}
    qreal getRedness()
    {
        return redness;
    }
    void setRedness(qreal val)
    {
        redness = val;
        colorize->setStrength(redness);
        this->update();
//        qDebug() << redness;
    }

public slots:
    void showEvent(QShowEvent *)
    {
        animation->start();
    }

private:
    qreal redness;
    QGraphicsColorizeEffect * colorize;
    QPropertyAnimation * animation;

};

and here is the main.cpp

#include <QApplication>
#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

Hope that helps.

Upvotes: 2

Related Questions