├── .gitignore ├── LICENSE ├── Qt-RandomVerification.pro ├── README.md ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── mainwindow.ui ├── random_verification ├── captchalabel.cpp ├── captchalabel.h ├── captchamovablelabel.cpp └── captchamovablelabel.h └── 截图.gif /.gitignore: -------------------------------------------------------------------------------- 1 | # This file is used to ignore files which are generated 2 | # ---------------------------------------------------------------------------- 3 | 4 | *~ 5 | *.autosave 6 | *.a 7 | *.core 8 | *.moc 9 | *.o 10 | *.obj 11 | *.orig 12 | *.rej 13 | *.so 14 | *.so.* 15 | *_pch.h.cpp 16 | *_resource.rc 17 | *.qm 18 | .#* 19 | *.*# 20 | core 21 | !core/ 22 | tags 23 | .DS_Store 24 | .directory 25 | *.debug 26 | Makefile* 27 | *.prl 28 | *.app 29 | moc_*.cpp 30 | ui_*.h 31 | qrc_*.cpp 32 | Thumbs.db 33 | *.res 34 | *.rc 35 | /.qmake.cache 36 | /.qmake.stash 37 | 38 | # qtcreator generated files 39 | *.pro.user* 40 | 41 | # xemacs temporary files 42 | *.flc 43 | 44 | # Vim temporary files 45 | .*.swp 46 | 47 | # Visual Studio generated files 48 | *.ib_pdb_index 49 | *.idb 50 | *.ilk 51 | *.pdb 52 | *.sln 53 | *.suo 54 | *.vcproj 55 | *vcproj.*.*.user 56 | *.ncb 57 | *.sdf 58 | *.opensdf 59 | *.vcxproj 60 | *vcxproj.* 61 | 62 | # MinGW generated files 63 | *.Debug 64 | *.Release 65 | 66 | # Python byte code 67 | *.pyc 68 | 69 | # Binaries 70 | # -------- 71 | *.dll 72 | *.exe 73 | 74 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Qt-RandomVerification.pro: -------------------------------------------------------------------------------- 1 | QT += core gui 2 | 3 | greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 | 5 | CONFIG += c++11 6 | 7 | # The following define makes your compiler emit warnings if you use 8 | # any Qt feature that has been marked deprecated (the exact warnings 9 | # depend on your compiler). Please consult the documentation of the 10 | # deprecated API in order to know how to port your code away from it. 11 | DEFINES += QT_DEPRECATED_WARNINGS 12 | 13 | # You can also make your code fail to compile if it uses deprecated APIs. 14 | # In order to do so, uncomment the following line. 15 | # You can also select to disable deprecated APIs only up to a certain version of Qt. 16 | #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 17 | 18 | INCLUDEPATH += random_verification 19 | 20 | SOURCES += \ 21 | random_verification/captchalabel.cpp \ 22 | random_verification/captchamovablelabel.cpp \ 23 | main.cpp \ 24 | mainwindow.cpp 25 | 26 | HEADERS += \ 27 | random_verification/captchalabel.h \ 28 | random_verification/captchamovablelabel.h \ 29 | mainwindow.h 30 | 31 | FORMS += \ 32 | mainwindow.ui 33 | 34 | # Default rules for deployment. 35 | qnx: target.path = /tmp/$${TARGET}/bin 36 | else: unix:!android: target.path = /opt/$${TARGET}/bin 37 | !isEmpty(target.path): INSTALLS += target 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 一个趣味性的验证码控件 2 | 3 | - 字符变换动画 4 | - 噪音动画 5 | - 可拖动交互 6 | 7 | ![截图](截图.gif) -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | 3 | #include 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | QApplication a(argc, argv); 8 | MainWindow w; 9 | w.show(); 10 | return a.exec(); 11 | } 12 | -------------------------------------------------------------------------------- /mainwindow.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | #include "ui_mainwindow.h" 3 | 4 | MainWindow::MainWindow(QWidget *parent) 5 | : QMainWindow(parent) 6 | , ui(new Ui::MainWindow) 7 | { 8 | ui->setupUi(this); 9 | } 10 | 11 | MainWindow::~MainWindow() 12 | { 13 | delete ui; 14 | } 15 | 16 | 17 | void MainWindow::on_pushButton_clicked() 18 | { 19 | QString text = ui->lineEdit->text(); 20 | if (ui->widget->match(text)) 21 | ui->pushButton->setText("验证通过"); 22 | else 23 | ui->pushButton->setText("验证失败"); 24 | } 25 | -------------------------------------------------------------------------------- /mainwindow.h: -------------------------------------------------------------------------------- 1 | #ifndef MAINWINDOW_H 2 | #define MAINWINDOW_H 3 | 4 | #include 5 | 6 | QT_BEGIN_NAMESPACE 7 | namespace Ui { class MainWindow; } 8 | QT_END_NAMESPACE 9 | 10 | class MainWindow : public QMainWindow 11 | { 12 | Q_OBJECT 13 | 14 | public: 15 | MainWindow(QWidget *parent = nullptr); 16 | ~MainWindow(); 17 | 18 | private slots: 19 | void on_pushButton_clicked(); 20 | 21 | private: 22 | Ui::MainWindow *ui; 23 | }; 24 | #endif // MAINWINDOW_H 25 | -------------------------------------------------------------------------------- /mainwindow.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 291 10 | 155 11 | 12 | 13 | 14 | MainWindow 15 | 16 | 17 | 18 | 19 | 20 | 40 21 | 10 22 | 181 23 | 71 24 | 25 | 26 | 27 | 28 | 29 | 30 | 30 31 | 90 32 | 113 33 | 20 34 | 35 | 36 | 37 | 38 | 39 | 40 | 150 41 | 90 42 | 75 43 | 23 44 | 45 | 46 | 47 | 验证 48 | 49 | 50 | 51 | 52 | 53 | 54 | 0 55 | 0 56 | 291 57 | 23 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | CaptchaLabel 66 | QWidget 67 |
captchalabel.h
68 | 1 69 |
70 |
71 | 72 | 73 |
74 | -------------------------------------------------------------------------------- /random_verification/captchalabel.cpp: -------------------------------------------------------------------------------- 1 | #include "captchalabel.h" 2 | 3 | CaptchaLabel::CaptchaLabel(QWidget *parent) : QWidget(parent) 4 | { 5 | initView(); 6 | // 这里延迟,等待布局结束 7 | QTimer::singleShot(0, [=]{ 8 | initData(); 9 | refresh(); 10 | }); 11 | } 12 | 13 | void CaptchaLabel::initView() 14 | { 15 | // 初始化控件 16 | for (int i = 0; i < CAPTCHAR_COUNT; i++) 17 | { 18 | charLabels[i] = new CaptchaMovableLabel(this); 19 | charLabels[i]->move(0, 0); 20 | } 21 | 22 | // 初始化时钟 23 | movingTimer.setInterval(30); 24 | movingTimer.setSingleShot(false); 25 | movingTimer.start(); 26 | connect(&movingTimer, SIGNAL(timeout()), this, SLOT(moveNoiseLines())); 27 | } 28 | 29 | void CaptchaLabel::initData() 30 | { 31 | // 初始化噪音线 32 | auto getRandomColor = [=]{ 33 | return QColor(qrand() % 255, qrand() % 255, qrand() % 255); 34 | }; 35 | int w = width(), h = height(); 36 | int count = w * h / 400; 37 | int penW = qMin(w, h) / 15; 38 | for (int i = 0; i < count; i++) 39 | { 40 | lineStarts.append(QPointF(qrand() % w, qrand() % h)); 41 | lineEnds.append(QPointF(qrand() % w, qrand() % h)); 42 | startsV.append(QPointF((qrand() % 30 - 15) / 10.0, (qrand() % 30 - 15) / 10.0)); 43 | endsV.append(QPointF((qrand() % 30 - 15) / 10.0, (qrand() % 30 - 15) / 10.0)); 44 | lineWidths.append(qrand() % penW + 1); 45 | lineColor1s.append(getRandomColor()); 46 | lineColor2s.append(getRandomColor()); 47 | } 48 | } 49 | 50 | void CaptchaLabel::setRefreshProgress(int g) 51 | { 52 | this->refreshProgress = g; 53 | update(); 54 | } 55 | 56 | int CaptchaLabel::getRefreshProgress() 57 | { 58 | return refreshProgress; 59 | } 60 | 61 | bool CaptchaLabel::isNoAni() 62 | { 63 | return refreshProgress == 100; 64 | } 65 | 66 | void CaptchaLabel::moveNoiseLines() 67 | { 68 | int w = width(), h = height(); 69 | double vBase = 100.0; // 大概最快要3秒钟走完 70 | 71 | for (int i = 0; i < lineStarts.size(); i++) 72 | { 73 | QPointF& pos = lineStarts[i]; 74 | pos += startsV.at(i); 75 | if (pos.x() < 0) 76 | startsV[i].setX(qrand() % w / vBase); 77 | else if (pos.x() > w) 78 | startsV[i].setX(- qrand() % w / vBase); 79 | if (pos.y() < 0) 80 | startsV[i].setY(qrand() % h / vBase); 81 | else if (pos.y() > h) 82 | startsV[i].setY(- qrand() % h / vBase); 83 | } 84 | 85 | 86 | for (int i = 0; i < lineEnds.size(); i++) 87 | { 88 | QPointF& pos = lineEnds[i]; 89 | pos += endsV.at(i); 90 | if (pos.x() < 0) 91 | endsV[i].setX(qrand() % w / vBase); 92 | else if (pos.x() > w) 93 | endsV[i].setX(- qrand() % w / vBase); 94 | if (pos.y() < 0) 95 | endsV[i].setY(qrand() % h / vBase); 96 | else if (pos.y() > h) 97 | endsV[i].setY(- qrand() % h / vBase); 98 | } 99 | 100 | update(); 101 | } 102 | void CaptchaLabel::refresh() 103 | { 104 | int width = this->width(); 105 | int height = this->height(); 106 | // 清空全部内容 107 | for (int i = 0; i < CAPTCHAR_COUNT; i++) 108 | charLabels[i]->hide(); 109 | 110 | refreshProgress = -1; 111 | update(); 112 | 113 | // 获取背景底色 114 | QPixmap rend(this->size()); 115 | render(&rend); 116 | QColor bgColor = rend.toImage().pixelColor(width/2, height/2); 117 | int br = bgColor.red(), bg = bgColor.green(), bb = bgColor.blue(); 118 | 119 | // 开始随机生成 120 | const int border = 10; 121 | int leftest = width / border; 122 | int topest = height / border; 123 | int wid = width - leftest * 2; 124 | int hei = height - topest * 2; 125 | for (int i = 0; i < CAPTCHAR_COUNT; i++) 126 | { 127 | auto label = charLabels[i]; 128 | 129 | // 随机大小 130 | QFont font; 131 | font.setPointSize( qrand() % 8 + 22 ); 132 | label->setFont(font); 133 | 134 | // 随机旋转 135 | label->setAngle( qrand() % (CAPTCHA_CHAR_ANGLE_MAX*2) - CAPTCHA_CHAR_ANGLE_MAX); 136 | 137 | // 生成随机字符 138 | const QString pool = "QWERTYUIOPASDFGHJKLZXCVBNM"; 139 | QChar rc = pool.at(qrand() % pool.size()); 140 | // 此时会调整大小,setText必须在setFont之后 141 | label->setText(rc); 142 | 143 | // 生成随机位置(排除边缘) 144 | int left = leftest + wid * i / CAPTCHAR_COUNT; 145 | int right = leftest + wid * (i+1) / CAPTCHAR_COUNT - label->width(); 146 | int x = qrand() % qMax(right-left, 1) + left; 147 | int y = qrand() % qMax(hei - label->height(), 1) + topest; 148 | label->show(); // 之前是hide状态 149 | QPropertyAnimation * ani = new QPropertyAnimation(label, "pos"); 150 | ani->setStartValue(label->pos()); 151 | ani->setEndValue(QPoint(x, y)); 152 | ani->setDuration(qrand() % (CAPTCHA_REFRESH_DURATION/2) + CAPTCHA_REFRESH_DURATION/2); 153 | ani->setEasingCurve(QEasingCurve::OutQuart); 154 | ani->start(); 155 | connect(ani, SIGNAL(finished()), ani, SLOT(deleteLater())); 156 | 157 | // 生成随机颜色,且必须和背景颜色有区分度 158 | QColor color; 159 | while (true) 160 | { 161 | int r = qrand() % 255; 162 | int g = qrand() % 255; 163 | int b = qrand() % 255; 164 | if (abs(r-br) + abs(g-bg) + abs(b-bb) > 383) 165 | { 166 | color = QColor(r, g, b); 167 | break; 168 | } 169 | } 170 | label->setColor(color); 171 | 172 | label->startRefreshAnimation(); 173 | } 174 | 175 | // 生成噪音点 176 | int count = wid * hei / border; // 点的数量 177 | if (noisePoints.size() == 0) // 第一次 178 | { 179 | for (int i = 0; i < count; i++) 180 | { 181 | int x = qrand() % width; 182 | int y = qrand() % height; 183 | noisePoints.append(QPoint(x, y / 2)); 184 | noisePoints2.append(QPoint(x, y)); 185 | pointColors.append(QColor(qrand() % 255, qrand() % 255, qrand() % 255)); 186 | } 187 | } 188 | else 189 | { 190 | noisePoints = noisePoints2; 191 | count = noisePoints.size(); 192 | 193 | noisePoints2.clear(); 194 | for (int i = 0; i < count; i++) 195 | { 196 | noisePoints2.append(QPoint(qrand() % width, qrand() % height)); 197 | } 198 | } 199 | 200 | // 生成噪音线 201 | 202 | QPropertyAnimation* ani = new QPropertyAnimation(this, "refreshProgress"); 203 | ani->setStartValue(0); 204 | ani->setEndValue(100); 205 | ani->setDuration(qrand() % (CAPTCHA_REFRESH_DURATION) + CAPTCHA_REFRESH_DURATION); 206 | ani->start(); 207 | connect(ani, SIGNAL(finished()), ani, SLOT(deleteLater())); 208 | } 209 | 210 | /** 211 | * 判断能否匹配 212 | */ 213 | bool CaptchaLabel::match(QString input) 214 | { 215 | // 根据label的位置排序 216 | std::sort(charLabels, charLabels+CAPTCHAR_COUNT, [=](QLabel* a, QLabel* b){ 217 | if (a->pos().x() == b->pos().x()) 218 | return a->pos().y() < b->pos().y(); 219 | return a->pos().x() < b->pos().x(); 220 | }); 221 | // 按顺序组合成新的字符串 222 | QString captcha; 223 | for (int i = 0; i < CAPTCHAR_COUNT; i++) 224 | captcha += charLabels[i]->text(); 225 | // 进行比较 226 | if (input.toUpper() == captcha) 227 | return true; 228 | 229 | // 记录失败 230 | matchFailCount++; 231 | if (matchFailCount >= autoRefreshMax // 达到刷新的次数 232 | || matchFailAndRefreshCount > 2) // 多次错误导致刷新 233 | { 234 | refresh(); 235 | matchFailAndRefreshCount++; 236 | matchFailCount = 0; 237 | } 238 | return false; 239 | } 240 | 241 | void CaptchaLabel::paintEvent(QPaintEvent *) 242 | { 243 | QPainter painter(this); 244 | 245 | if (refreshProgress == -1) // 不画,可能需要获取背景颜色 246 | return ; 247 | 248 | // 画噪音点 249 | if (isNoAni()) 250 | { 251 | // 显示随机的点 252 | for (int i = 0; i < noisePoints2.size(); i++) 253 | { 254 | painter.setPen(pointColors.at(i)); 255 | painter.drawPoint(noisePoints2.at(i)); 256 | } 257 | } 258 | else 259 | { 260 | // 动画过程中的点的移动 261 | double newProp = refreshProgress / 100.0; 262 | double oldProp = 1.0 - newProp; 263 | int count = qMin(noisePoints.size(), noisePoints2.size()); 264 | for (int i = 0; i < count; i++) 265 | { 266 | QPoint pt1 = noisePoints.at(i); 267 | QPoint pt2 = noisePoints2.at(i); 268 | QPoint pt( pt1.x() * oldProp + pt2.x() * newProp, 269 | pt1.y() * oldProp + pt2.y() * newProp ); 270 | painter.setPen(pointColors.at(i)); 271 | painter.drawPoint(pt); 272 | } 273 | } 274 | 275 | // 画噪音线 276 | painter.setRenderHint(QPainter::Antialiasing); 277 | for (int i = 0; i < lineStarts.size(); i++) 278 | { 279 | QLinearGradient grad(lineStarts.at(i), lineEnds.at(i)); 280 | grad.setColorAt(0, lineColor1s.at(i)); 281 | grad.setColorAt(1, lineColor2s.at(i)); 282 | painter.setPen(QPen(grad, lineWidths.at(i))); 283 | painter.drawLine(lineStarts.at(i), lineEnds.at(i)); 284 | } 285 | } 286 | 287 | void CaptchaLabel::mouseReleaseEvent(QMouseEvent *event) 288 | { 289 | if (QRect(0,0,width(),height()).contains(event->pos())) 290 | refresh(); 291 | QWidget::mouseReleaseEvent(event); 292 | } 293 | 294 | -------------------------------------------------------------------------------- /random_verification/captchalabel.h: -------------------------------------------------------------------------------- 1 | #ifndef CAPTCHALABEL_H 2 | #define CAPTCHALABEL_H 3 | 4 | #include "captchamovablelabel.h" 5 | #include 6 | 7 | #define CAPTCHAR_COUNT 4 // 验证码字符数量 8 | 9 | class CaptchaLabel : public QWidget 10 | { 11 | Q_OBJECT 12 | Q_PROPERTY(int refreshProgress READ getRefreshProgress WRITE setRefreshProgress) 13 | public: 14 | CaptchaLabel(QWidget* parent = nullptr); 15 | 16 | void refresh(); 17 | bool match(QString input); 18 | 19 | private: 20 | void initView(); 21 | void initData(); 22 | void setRefreshProgress(int g); 23 | int getRefreshProgress(); 24 | bool isNoAni(); 25 | 26 | private slots: 27 | void moveNoiseLines(); 28 | 29 | protected: 30 | void paintEvent(QPaintEvent* ) override; 31 | void mouseReleaseEvent(QMouseEvent *event) override; 32 | 33 | private: 34 | CaptchaMovableLabel* charLabels[CAPTCHAR_COUNT]; // Label控件 35 | QList noisePoints; // 噪音点 36 | QList pointColors; // 点的颜色 37 | 38 | QList lineStarts; // 噪音线起始点 39 | QList lineEnds; // 噪音先结束点 40 | QList startsV; // 起始点的移动速度(带方向) 41 | QList endsV; // 结束点的速度(带方向) 42 | QList lineColor1s; // 线的渐变色1 43 | QList lineColor2s; // 线的渐变色2 44 | QList lineWidths; 45 | QTimer movingTimer; 46 | 47 | int refreshProgress = 100; 48 | QList noisePoints2; // 新的位置 49 | 50 | int autoRefreshMax = 2; // match错误几次后就自动刷新 51 | int matchFailCount = 0; // match错误次数 52 | int matchFailAndRefreshCount = 0; // 失败且导致刷新的次数,强行刷新 53 | }; 54 | 55 | #endif // CAPTCHALABEL_H 56 | -------------------------------------------------------------------------------- /random_verification/captchamovablelabel.cpp: -------------------------------------------------------------------------------- 1 | #include "captchamovablelabel.h" 2 | 3 | 4 | CaptchaMovableLabel::CaptchaMovableLabel(QWidget *parent) : QLabel(parent) 5 | { 6 | effect.setOffset(0, 0); 7 | // effect.setBlurRadius(8); 8 | setGraphicsEffect(&effect); 9 | 10 | movingTimer.setInterval(30); 11 | movingTimer.setSingleShot(false); 12 | connect(&movingTimer, SIGNAL(timeout()), this, SLOT(slotMovePos())); 13 | } 14 | 15 | void CaptchaMovableLabel::setAngle(int angle) 16 | { 17 | this->prevAngle = this->angle; 18 | this->angle = angle; 19 | } 20 | 21 | void CaptchaMovableLabel::setColor(QColor color) 22 | { 23 | this->prevColor = this->color; 24 | this->color = color; 25 | 26 | moveR = qrand() % 5; 27 | moveG = qrand() % 5; 28 | moveB = qrand() % 5; 29 | movingTimer.start(); 30 | } 31 | 32 | void CaptchaMovableLabel::setText(QString text) 33 | { 34 | this->prevCh = this->ch; 35 | this->ch = text; 36 | 37 | // 计算合适的高度 38 | QFontMetrics fm(this->font()); 39 | double w = fm.horizontalAdvance(text)+2; 40 | double h = fm.height(); 41 | 42 | const double PI = 3.141592; 43 | int xieHalf = sqrt(w*w/4+h*h/4); // 斜边的一半 44 | double a = atan(w/h) + CAPTCHA_CHAR_ANGLE_MAX * PI / 180; // 最大的倾斜角度 45 | int w2 = xieHalf * sin(a) * 2; 46 | 47 | a = atan(w/h) - CAPTCHA_CHAR_ANGLE_MAX * PI / 180; 48 | int h2 = xieHalf * cos(a) * 2; 49 | 50 | resize(w2, h2); 51 | } 52 | 53 | void CaptchaMovableLabel::startRefreshAnimation() 54 | { 55 | if (!inited) // 第一次,直接显示,取消动画 56 | { 57 | inited = true; 58 | return ; 59 | } 60 | 61 | QPropertyAnimation* ani = new QPropertyAnimation(this, "refreshProgress"); 62 | ani->setStartValue(0); 63 | ani->setEndValue(100); 64 | ani->setDuration(qrand() % (CAPTCHA_REFRESH_DURATION / 3) + CAPTCHA_REFRESH_DURATION / 3); 65 | ani->start(); 66 | connect(ani, SIGNAL(finished()), ani, SLOT(deleteLater())); 67 | connect(ani, SIGNAL(finished()), &movingTimer, SLOT(start())); 68 | } 69 | 70 | QString CaptchaMovableLabel::text() 71 | { 72 | return ch; 73 | } 74 | 75 | void CaptchaMovableLabel::paintEvent(QPaintEvent *) 76 | { 77 | QPainter painter(this); 78 | painter.setFont(this->font()); 79 | painter.setRenderHint(QPainter::SmoothPixmapTransform); 80 | 81 | int w2 = width()/2, h2 = height()/2; 82 | painter.translate(w2, h2); // 平移到中心,绕中心点旋转 83 | 84 | if (isNoAni()) // 不在动画中,直接绘制 85 | { 86 | painter.setPen(color); 87 | painter.rotate(angle); 88 | painter.drawText(QRect(-w2, -h2, width(), height()), Qt::AlignCenter, ch); 89 | return ; 90 | } 91 | 92 | // 动画里面,前后渐变替换 93 | double newProp = refreshProgress / 100.0; 94 | double oldProp = 1.0 - newProp; 95 | 96 | double a = prevAngle * oldProp + angle * newProp + 0.5; 97 | painter.save(); 98 | painter.rotate(a); 99 | 100 | QColor c = prevColor; 101 | c.setAlpha(c.alpha() * oldProp); // 旧文字渐渐消失 102 | painter.setPen(c); 103 | painter.drawText(QRect(-w2,-h2,width(),height()), Qt::AlignCenter, prevCh); 104 | 105 | c = this->color; 106 | c.setAlpha(c.alpha() * newProp); // 新文字渐渐显示 107 | painter.setPen(c); 108 | painter.drawText(QRect(-w2, -h2, width(), height()), Qt::AlignCenter, ch); 109 | painter.restore(); 110 | } 111 | 112 | void CaptchaMovableLabel::mousePressEvent(QMouseEvent *ev) 113 | { 114 | if (ev->button() == Qt::LeftButton) 115 | { 116 | // 开始拖拽 117 | press_pos = ev->pos(); 118 | dragging = true; 119 | moved = false; 120 | this->raise(); 121 | movingTimer.stop(); 122 | 123 | startPressAnimation(200); 124 | 125 | return ev->accept(); 126 | } 127 | QLabel::mousePressEvent(ev); 128 | } 129 | 130 | void CaptchaMovableLabel::mouseMoveEvent(QMouseEvent *ev) 131 | { 132 | if (dragging && ev->buttons() & Qt::LeftButton) 133 | { 134 | if (!moved && (ev->pos() - press_pos).manhattanLength() < QApplication::startDragDistance()) 135 | { 136 | return QLabel::mouseMoveEvent(ev); // 还没到这时候 137 | } 138 | moved = true; 139 | move(this->pos() + ev->pos() - press_pos); 140 | ev->accept(); 141 | return ; 142 | } 143 | QLabel::mouseMoveEvent(ev); 144 | } 145 | 146 | void CaptchaMovableLabel::mouseReleaseEvent(QMouseEvent *ev) 147 | { 148 | if (dragging) 149 | { 150 | // 结束拖拽 151 | dragging = false; 152 | movingTimer.start(); 153 | 154 | startPressAnimation(0); 155 | } 156 | if (moved) 157 | return ev->accept(); 158 | QLabel::mouseReleaseEvent(ev); 159 | } 160 | 161 | void CaptchaMovableLabel::startPressAnimation(int end) 162 | { 163 | QPropertyAnimation* ani = new QPropertyAnimation(this, "pressProgress"); 164 | ani->setStartValue(pressProgress); 165 | ani->setEndValue(end); 166 | ani->setDuration(CAPTCHA_REFRESH_DURATION << 1); 167 | ani->start(); 168 | connect(ani, SIGNAL(finished()), ani, SLOT(deleteLater())); 169 | } 170 | 171 | void CaptchaMovableLabel::setRefreshProgress(int g) 172 | { 173 | this->refreshProgress = g; 174 | update(); 175 | } 176 | 177 | int CaptchaMovableLabel::getRefreshProgress() 178 | { 179 | return refreshProgress; 180 | } 181 | 182 | bool CaptchaMovableLabel::isNoAni() 183 | { 184 | return refreshProgress == 100; 185 | } 186 | 187 | void CaptchaMovableLabel::setPressProgress(int g) 188 | { 189 | this->pressProgress = g; 190 | double off = g / 100; 191 | effect.setBlurRadius(g / 20.0); 192 | effect.setOffset(-off, off); 193 | } 194 | 195 | int CaptchaMovableLabel::getPressProgress() 196 | { 197 | return pressProgress; 198 | } 199 | 200 | void CaptchaMovableLabel::slotMovePos() 201 | { 202 | if (refreshProgress < 100) 203 | return ; 204 | 205 | int val = color.red() + moveR; 206 | if ( val > 255) 207 | { 208 | val = 255; 209 | moveR = - qrand() % 5; 210 | } 211 | else if (val < 0) 212 | { 213 | val = 0; 214 | moveR = - qrand() % 5; 215 | } 216 | color.setRed(val); 217 | 218 | val = color.green() + moveG; 219 | if ( val > 255) 220 | { 221 | val = 255; 222 | moveG = - qrand() % 5; 223 | } 224 | else if (val < 0) 225 | { 226 | val = 0; 227 | moveG = - qrand() % 5; 228 | } 229 | color.setGreen(val); 230 | 231 | val = color.blue() + moveB; 232 | if ( val > 255) 233 | { 234 | val = 255; 235 | moveB = - qrand() % 5; 236 | } 237 | else if (val < 0) 238 | { 239 | val = 0; 240 | moveB = - qrand() % 5; 241 | } 242 | color.setBlue(val); 243 | } 244 | -------------------------------------------------------------------------------- /random_verification/captchamovablelabel.h: -------------------------------------------------------------------------------- 1 | #ifndef CAPTCHAMOVABLELABEL_H 2 | #define CAPTCHAMOVABLELABEL_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #define CAPTCHA_REFRESH_DURATION 300 // 刷新的动画时长 17 | #define CAPTCHA_CHAR_ANGLE_MAX 20 // 最大旋转角:20° 18 | #define CAPTCHA_SHADOW_BLUR_MAX 80 // 最大的阴影模糊半径 19 | 20 | class CaptchaMovableLabel : public QLabel 21 | { 22 | Q_OBJECT 23 | Q_PROPERTY(int refreshProgress READ getRefreshProgress WRITE setRefreshProgress) 24 | Q_PROPERTY(int pressProgress READ getPressProgress WRITE setPressProgress) 25 | public: 26 | CaptchaMovableLabel(QWidget* parent); 27 | 28 | void setAngle(int angle); 29 | void setColor(QColor color); 30 | void setText(QString ch); 31 | void startRefreshAnimation(); 32 | void setMoveBorder(QRect rect); 33 | 34 | QString text(); 35 | 36 | protected: 37 | void paintEvent(QPaintEvent *) override; 38 | void mousePressEvent(QMouseEvent *ev) override; 39 | void mouseMoveEvent(QMouseEvent *ev) override; 40 | void mouseReleaseEvent(QMouseEvent *ev) override; 41 | 42 | private: 43 | void startPressAnimation(int end); 44 | void setRefreshProgress(int g); 45 | int getRefreshProgress(); 46 | inline bool isNoAni(); 47 | void setPressProgress(int g); 48 | int getPressProgress(); 49 | 50 | private slots: 51 | void slotMovePos(); 52 | 53 | private: 54 | QPoint press_pos; 55 | bool dragging = false; 56 | bool moved = false; 57 | QGraphicsDropShadowEffect effect; 58 | 59 | QString ch; 60 | QColor color; 61 | int angle = 0; 62 | int refreshProgress = 100; 63 | 64 | QString prevCh; 65 | QColor prevColor; 66 | int prevAngle = 0; 67 | QString prevChar; 68 | 69 | int pressProgress = 0; 70 | 71 | bool inited = false; 72 | QTimer movingTimer; 73 | int moveR, moveG, moveB; 74 | }; 75 | 76 | #endif // CAPTCHAMOVABLELABEL_H 77 | -------------------------------------------------------------------------------- /截图.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iwxyi/Qt-RandomVerification/34c7ade86ce9f49a2c03f9cfb2bdb48ff6cb85df/截图.gif --------------------------------------------------------------------------------