FluentUI/src/FluCaptcha.cpp

72 lines
2.1 KiB
C++
Raw Normal View History

2023-08-18 11:46:02 +08:00
#include "FluCaptcha.h"
#include <QTime>
#include <QChar>
#include <QPainter>
#include <QRandomGenerator>
2024-04-11 14:51:43 +08:00
int generaNumber(int number) {
return QRandomGenerator::global()->bounded(0, number);
}
FluCaptcha::FluCaptcha(QQuickItem *parent) : QQuickPaintedItem(parent) {
_ignoreCase = false;
QFont fontStyle;
2024-04-11 20:29:59 +08:00
#ifdef Q_OS_WIN
fontStyle.setFamily("微软雅黑");
#endif
2024-04-11 14:51:43 +08:00
fontStyle.setPixelSize(28);
fontStyle.setBold(true);
font(fontStyle);
2023-08-18 11:46:02 +08:00
setWidth(180);
setHeight(80);
refresh();
}
2024-04-11 14:51:43 +08:00
void FluCaptcha::paint(QPainter *painter) {
2023-08-18 11:46:02 +08:00
painter->save();
2024-04-11 14:51:43 +08:00
painter->fillRect(boundingRect().toRect(), QColor(255, 255, 255, 255));
2023-08-18 11:46:02 +08:00
QPen pen;
painter->setFont(_font);
2024-04-11 14:51:43 +08:00
for (int i = 0; i < 100; i++) {
pen = QPen(QColor(generaNumber(256), generaNumber(256), generaNumber(256)));
2023-08-18 11:46:02 +08:00
painter->setPen(pen);
2024-04-11 14:51:43 +08:00
painter->drawPoint(generaNumber(180), generaNumber(80));
2023-08-18 11:46:02 +08:00
}
2024-04-11 14:51:43 +08:00
for (int i = 0; i < 5; i++) {
pen = QPen(QColor(generaNumber(256), generaNumber(256), generaNumber(256)));
2023-08-18 11:46:02 +08:00
painter->setPen(pen);
2024-04-11 14:51:43 +08:00
painter->drawLine(generaNumber(180), generaNumber(80), generaNumber(180), generaNumber(80));
2023-08-18 11:46:02 +08:00
}
2024-04-11 14:51:43 +08:00
for (int i = 0; i < 4; i++) {
pen = QPen(QColor(generaNumber(255), generaNumber(255), generaNumber(255)));
2023-08-18 11:46:02 +08:00
painter->setPen(pen);
2024-06-28 17:09:23 +08:00
painter->drawText(15 + 35 * i, 10 + generaNumber(15), 30, 40, Qt::AlignCenter,
QString(_code[i]));
2023-08-18 11:46:02 +08:00
}
painter->restore();
}
2024-04-11 14:51:43 +08:00
void FluCaptcha::refresh() {
2023-08-18 11:46:02 +08:00
this->_code.clear();
2024-04-11 14:51:43 +08:00
for (int i = 0; i < 4; ++i) {
int num = generaNumber(3);
if (num == 0) {
this->_code += QString::number(generaNumber(10));
} else if (num == 1) {
2023-08-18 11:46:02 +08:00
int temp = 'A';
2024-04-11 14:51:43 +08:00
this->_code += static_cast<QChar>(temp + generaNumber(26));
} else if (num == 2) {
2023-08-18 11:46:02 +08:00
int temp = 'a';
2024-04-11 14:51:43 +08:00
this->_code += static_cast<QChar>(temp + generaNumber(26));
2023-08-18 11:46:02 +08:00
}
}
update();
}
2024-04-11 14:51:43 +08:00
[[maybe_unused]] bool FluCaptcha::verify(const QString &code) {
if (_ignoreCase) {
2023-09-13 15:11:22 +08:00
return this->_code.toUpper() == code.toUpper();
}
2023-08-18 11:46:02 +08:00
return this->_code == code;
}