在平時的寫做過程當中,常常須要將一些操做動做和效果圖截圖成gif格式,使得涵蓋的信息更全面更生動,有時候能夠將整個操做過程和運行效果錄製成MP4,可是文件體積比較大,並且不少網站不便於上傳,基本上都支持gif動圖,通常一個5秒左右的gif,800*600分辨率,能夠很好的控制在500KB內,這樣就比較完美的支持各大網站上傳動圖。 最開始使用的是ScreenGif.exe,用了好久,感受還能夠,後面一個朋友推薦用LICEcap.exe,體積更小,壓縮比更高,再到後來發現有個gif.h開源的類,調用其中的方法能夠實現將多張圖片合併到一張gif中去,並且仍是跨平臺的,本人親自在WIN+UBUNTU測試成功。 最初的代碼是倪大俠給的,我在此基礎上從新完善了下,使得能夠直接拖動窗體大小來改變錄屏區域的大小。增長了對Qt4和其餘編譯器的支持。linux
#ifndef GIFWIDGET_H #define GIFWIDGET_H /** * GIF錄屏控件 做者:feiyangqingyun(QQ:517216493) 2019-4-3 * 1:可設置要錄製屏幕的寬高,支持右下角直接拉動改變. * 2:可設置變寬的寬度 * 3:可設置錄屏控件的背景顏色 * 4:可設置錄製的幀數 * 5:錄製區域可自由拖動選擇 */ #include <QDialog> #include "gif.h" class QLineEdit; class QLabel; #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT GifWidget : public QDialog #else class GifWidget : public QDialog #endif { Q_OBJECT Q_PROPERTY(int borderWidth READ getBorderWidth WRITE setBorderWidth) Q_PROPERTY(QColor bgColor READ getBgColor WRITE setBgColor) public: static GifWidget *Instance(); explicit GifWidget(QWidget *parent = 0); protected: bool eventFilter(QObject *watched, QEvent *event); void resizeEvent(QResizeEvent *); void paintEvent(QPaintEvent *); private: static QScopedPointer<GifWidget> self; QWidget *widgetTop; //標題欄 QWidget *widgetMain; //中間部分 QWidget *widgetBottom; //底部欄 QLineEdit *txtFps; //幀率輸入框 QLineEdit *txtWidth; //寬度輸入框 QLineEdit *txtHeight; //高度輸入框 QPushButton *btnStart; //開始按鈕 QLabel *labStatus; //顯示狀態信息 int fps; //幀數 100爲1s int borderWidth; //邊框寬度 QColor bgColor; //背景顏色 int count; //幀數計數 QString fileName; //保存文件名稱 QRect rectGif; //截屏區域 QTimer *timer; //截屏定時器 Gif gif; //gif類對象 Gif::GifWriter *gifWriter; //gif寫入對象 public: int getBorderWidth() const; QColor getBgColor() const; private slots: void initControl(); void initForm(); void saveImage(); void record(); void closeAll(); void resizeForm(); public Q_SLOTS: void setBorderWidth(int borderWidth); void setBgColor(const QColor &bgColor); }; #endif // GIFWIDGET_H
#pragma execution_character_set("utf-8") #include "gifwidget.h" #include "qmutex.h" #include "qlabel.h" #include "qlineedit.h" #include "qpushbutton.h" #include "qlayout.h" #include "qpainter.h" #include "qevent.h" #include "qstyle.h" #include "qpixmap.h" #include "qtimer.h" #include "qdatetime.h" #include "qapplication.h" #include "qdesktopwidget.h" #include "qdesktopservices.h" #include "qfiledialog.h" #include "qurl.h" #include "qdebug.h" #if (QT_VERSION > QT_VERSION_CHECK(5,0,0)) #include "qscreen.h" #endif QScopedPointer<GifWidget> GifWidget::self; GifWidget *GifWidget::Instance() { if (self.isNull()) { static QMutex mutex; QMutexLocker locker(&mutex); if (self.isNull()) { self.reset(new GifWidget); } } return self.data(); } GifWidget::GifWidget(QWidget *parent) : QDialog(parent) { this->initControl(); this->initForm(); } bool GifWidget::eventFilter(QObject *watched, QEvent *event) { static QPoint mousePoint; static bool mousePressed = false; QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->type() == QEvent::MouseButtonPress) { if (mouseEvent->button() == Qt::LeftButton) { mousePressed = true; mousePoint = mouseEvent->globalPos() - this->pos(); return true; } } else if (mouseEvent->type() == QEvent::MouseButtonRelease) { mousePressed = false; return true; } else if (mouseEvent->type() == QEvent::MouseMove) { if (mousePressed && (mouseEvent->buttons() && Qt::LeftButton)) { this->move(mouseEvent->globalPos() - mousePoint); return true; } } return QWidget::eventFilter(watched, event); } void GifWidget::resizeEvent(QResizeEvent *e) { //拉動右下角改變大小自動賦值 txtWidth->setText(QString::number(widgetMain->width())); txtHeight->setText(QString::number(widgetMain->height())); QDialog::resizeEvent(e); } void GifWidget::paintEvent(QPaintEvent *) { int width = txtWidth->text().toInt(); int height = txtHeight->text().toInt(); rectGif = QRect(borderWidth, widgetTop->height(), width - (borderWidth * 2), height); QPainter painter(this); painter.setPen(Qt::NoPen); painter.setBrush(bgColor); painter.drawRoundedRect(this->rect(), 5, 5); painter.setCompositionMode(QPainter::CompositionMode_Clear); painter.fillRect(rectGif, Qt::SolidPattern); } int GifWidget::getBorderWidth() const { return this->borderWidth; } QColor GifWidget::getBgColor() const { return this->bgColor; } void GifWidget::initControl() { this->setObjectName("GifWidget"); this->resize(800, 600); this->setSizeGripEnabled(true); QVBoxLayout *verticalLayout = new QVBoxLayout(this); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName("verticalLayout"); verticalLayout->setContentsMargins(0, 0, 0, 0); widgetTop = new QWidget(this); widgetTop->setObjectName("widgetTop"); widgetTop->setMinimumSize(QSize(0, 35)); widgetTop->setMaximumSize(QSize(16777215, 35)); QHBoxLayout *layoutTop = new QHBoxLayout(widgetTop); layoutTop->setSpacing(0); layoutTop->setContentsMargins(11, 11, 11, 11); layoutTop->setObjectName("layoutTop"); layoutTop->setContentsMargins(0, 0, 0, 0); QPushButton *btnIcon = new QPushButton(widgetTop); btnIcon->setObjectName("btnIcon"); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(btnIcon->sizePolicy().hasHeightForWidth()); btnIcon->setSizePolicy(sizePolicy); btnIcon->setMinimumSize(QSize(35, 0)); btnIcon->setFlat(true); layoutTop->addWidget(btnIcon); QLabel *labTitle = new QLabel(widgetTop); labTitle->setObjectName("labTitle"); layoutTop->addWidget(labTitle); QSpacerItem *horizontalSpacer = new QSpacerItem(87, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); layoutTop->addItem(horizontalSpacer); QPushButton *btnClose = new QPushButton(widgetTop); btnClose->setObjectName("btnClose"); sizePolicy.setHeightForWidth(btnClose->sizePolicy().hasHeightForWidth()); btnClose->setSizePolicy(sizePolicy); btnClose->setMinimumSize(QSize(35, 0)); btnClose->setFocusPolicy(Qt::NoFocus); btnClose->setFlat(true); layoutTop->addWidget(btnClose); verticalLayout->addWidget(widgetTop); widgetMain = new QWidget(this); widgetMain->setObjectName("widgetMain"); QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(widgetMain->sizePolicy().hasHeightForWidth()); widgetMain->setSizePolicy(sizePolicy1); verticalLayout->addWidget(widgetMain); widgetBottom = new QWidget(this); widgetBottom->setObjectName("widgetBottom"); widgetBottom->setMinimumSize(QSize(0, 45)); widgetBottom->setMaximumSize(QSize(16777215, 45)); QHBoxLayout *layoutBottom = new QHBoxLayout(widgetBottom); layoutBottom->setSpacing(6); layoutBottom->setContentsMargins(11, 11, 11, 11); layoutBottom->setObjectName("layoutBottom"); layoutBottom->setContentsMargins(9, 9, -1, -1); QLabel *labFps = new QLabel(widgetBottom); labFps->setObjectName("labFps"); layoutBottom->addWidget(labFps); txtFps = new QLineEdit(widgetBottom); txtFps->setObjectName("txtFps"); txtFps->setMaximumSize(QSize(50, 16777215)); txtFps->setAlignment(Qt::AlignCenter); layoutBottom->addWidget(txtFps); QLabel *labWidth = new QLabel(widgetBottom); labWidth->setObjectName("labWidth"); layoutBottom->addWidget(labWidth); txtWidth = new QLineEdit(widgetBottom); txtWidth->setObjectName("txtWidth"); txtWidth->setEnabled(true); txtWidth->setMaximumSize(QSize(50, 16777215)); txtWidth->setAlignment(Qt::AlignCenter); layoutBottom->addWidget(txtWidth); QLabel *labHeight = new QLabel(widgetBottom); labHeight->setObjectName("labHeight"); layoutBottom->addWidget(labHeight); txtHeight = new QLineEdit(widgetBottom); txtHeight->setObjectName("txtHeight"); txtHeight->setEnabled(true); txtHeight->setMaximumSize(QSize(50, 16777215)); txtHeight->setAlignment(Qt::AlignCenter); layoutBottom->addWidget(txtHeight); labStatus = new QLabel(widgetBottom); labStatus->setObjectName("labStatus"); QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(labStatus->sizePolicy().hasHeightForWidth()); labStatus->setSizePolicy(sizePolicy2); labStatus->setAlignment(Qt::AlignCenter); layoutBottom->addWidget(labStatus); btnStart = new QPushButton(widgetBottom); btnStart->setObjectName("btnStart"); sizePolicy.setHeightForWidth(btnStart->sizePolicy().hasHeightForWidth()); btnStart->setSizePolicy(sizePolicy); layoutBottom->addWidget(btnStart); verticalLayout->addWidget(widgetBottom); labTitle->setText("GIF錄屏工具(QQ:517216493)"); labFps->setText("幀率"); labWidth->setText("寬度"); labHeight->setText("高度"); btnStart->setText("開始"); this->setWindowTitle(labTitle->text()); btnIcon->setIcon(style()->standardIcon(QStyle::SP_ComputerIcon)); btnClose->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); connect(btnClose, SIGNAL(clicked(bool)), this, SLOT(closeAll())); connect(btnStart, SIGNAL(clicked(bool)), this, SLOT(record())); connect(txtWidth, SIGNAL(editingFinished()), this, SLOT(resizeForm())); connect(txtHeight, SIGNAL(editingFinished()), this, SLOT(resizeForm())); } void GifWidget::initForm() { borderWidth = 3; bgColor = QColor(34, 163, 169); fps = 10; txtFps->setText(QString::number(fps)); gifWriter = 0; timer = new QTimer(this); timer->setInterval(100); connect(timer, SIGNAL(timeout()), this, SLOT(saveImage())); this->setAttribute(Qt::WA_TranslucentBackground); this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowStaysOnTopHint); this->installEventFilter(this); QStringList qss; qss.append("QLabel{color:#ffffff;}"); qss.append("#btnClose,#btnIcon{border:none;border-radius:0px;}"); qss.append("#btnClose:hover{background-color:#ff0000;}"); qss.append("#btnClose{border-top-right-radius:5px;}"); qss.append("#labTitle{font:bold 16px;}"); qss.append("#labStatus{font:15px;}"); this->setStyleSheet(qss.join("")); } void GifWidget::saveImage() { if (!gifWriter) { return; } #if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) //因爲qt4沒有RGBA8888,採用最接近RGBA8888的是ARGB32,顏色會有點誤差 QPixmap pix = QPixmap::grabWindow(0, x() + rectGif.x(), y() + rectGif.y(), rectGif.width(), rectGif.height()); QImage image = pix.toImage().convertToFormat(QImage::Format_ARGB32); #else QScreen *screen = QApplication::primaryScreen(); QPixmap pix = screen->grabWindow(0, x() + rectGif.x(), y() + rectGif.y(), rectGif.width(), rectGif.height()); QImage image = pix.toImage().convertToFormat(QImage::Format_RGBA8888); #endif gif.GifWriteFrame(gifWriter, image.bits(), rectGif.width(), rectGif.height(), fps); count++; labStatus->setText(QString("正在錄製 第 %1 幀").arg(count)); } void GifWidget::record() { if (btnStart->text() == "開始") { if (0 != gifWriter) { delete gifWriter; gifWriter = 0; } //先彈出文件保存對話框 //fileName = qApp->applicationDirPath() + "/" + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss.gif"); fileName = QFileDialog::getSaveFileName(this, "選擇保存位置", qApp->applicationDirPath() + "/", "gif圖片(*.gif)"); if (fileName.isEmpty()) { return; } int width = txtWidth->text().toInt(); int height = txtHeight->text().toInt(); fps = txtFps->text().toInt(); gifWriter = new Gif::GifWriter; bool bOk = gif.GifBegin(gifWriter, fileName.toLocal8Bit().data(), width, height, fps); if (!bOk) { delete gifWriter; gifWriter = 0; return; } count = 0; labStatus->setText("開始錄製..."); btnStart->setText("中止"); //延時啓動 timer->setInterval(1000 / fps); QTimer::singleShot(1000, timer, SLOT(start())); //saveImage(); } else { timer->stop(); gif.GifEnd(gifWriter); delete gifWriter; gifWriter = 0; labStatus->setText(QString("錄製完成 共 %1 幀").arg(count)); btnStart->setText("開始"); QDesktopServices::openUrl(QUrl(fileName)); } } void GifWidget::closeAll() { if (0 != gifWriter) { delete gifWriter; gifWriter = 0; } this->close(); } void GifWidget::resizeForm() { int width = txtWidth->text().toInt(); int height = txtHeight->text().toInt(); this->resize(width, height + widgetTop->height() + widgetBottom->height()); } void GifWidget::setBorderWidth(int borderWidth) { if (this->borderWidth != borderWidth) { this->borderWidth = borderWidth; this->update(); } } void GifWidget::setBgColor(const QColor &bgColor) { if (this->bgColor != bgColor) { this->bgColor = bgColor; this->update(); } }