QImage实现图片间渐变切换

来源:互联网 发布:儿童发音矫正软件 编辑:程序博客网 时间:2024/05/25 01:34

//declaration

#ifndefWIDGET_H
#defineWIDGET_H

#include<QLabel>
#include<QImage>
#include<QTimer>

class Widget :public QLabel
{
   Q_OBJECT
private:
   boolm_bFlag;//true:1->2;false:2->1;
   int per;

   //the switching images
   QImage m_image1;
   QImage m_image2;

   QTimer* m_timer;//to control the switch
public:
   Widget(QWidget *parent = 0);
   ~Widget();
privateslots:
   void timeoutSlot();//the handle to control theswitch
};

#endif //WIDGET_H

//implement

 

#include"widget.h"

Widget::Widget(QWidget*parent)
   : QLabel(parent)
{
   this->setFixedSize(240,320);

   //init
   m_bFlag = true;
   per = 0;
   m_image1 =QImage("./1.png").convertToFormat(QImage::Format_ARGB32);
   m_image2 =QImage("./2.png").convertToFormat(QImage::Format_ARGB32);
   this->setPixmap(QPixmap::fromImage(m_image1));

   m_timer = new QTimer(this);
   connect(m_timer,SIGNAL(timeout()),this,SLOT(timeoutSlot()));
   m_timer->start(100);


}

voidWidget::timeoutSlot()
{
   if(m_bFlag)
   {
       per ++;
   }
   else
   {
       per --;
   }

   QImageimage(m_image1.width(),m_image1.height(),QImage::Format_ARGB32);//constructan empty image
   for(int row = 0;row <image.width();row++)
   {
       for(int col = 0;col<image.height();col++)
       {
           //achieve every pixel in the two images
           QRgb rgb1 = m_image1.pixel(row,col);
           QRgb rgb2 = m_image2.pixel(row,col);

           //compute the pixel to be set into the new image
           QColor color;
           color.setRed(qRed(rgb1)*(1-(double)per/10)+qRed(rgb2)*((double)per/10));
           color.setGreen(qGreen(rgb1)*(1-(double)per/10)+qGreen(rgb2)*((double)per/10));
           color.setBlue(qBlue(rgb1)*(1-(double)per/10)+qBlue(rgb2)*((double)per/10));
           image.setPixel(row,col,color.rgba());
       }
   }

   this->setPixmap(QPixmap::fromImage(image));

   if( per >= 10)
   {
       m_bFlag = false;
   }
   else if( per <= 0 )
   {
       m_bFlag = true;
   }
}

Widget::~Widget()
{

}

//useage 

 

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

int main(intargc, char *argv[])
{
   QApplication a(argc, argv);
   Widget w;
#ifdefQ_OS_WIN
   w.setFixedSize(240,320);
   w.show();
#endif

#ifdefQ_OS_LINUX
   w.showFullScreen();
#endif

   return a.exec();
}

 

0 0
原创粉丝点击