在Qt Widget中绘制 HSV色环
HSV颜色模型(Hue, Saturation, Value),色调(H),饱和度(S),明度(V)
class qtColorWheel : public QWidget
{
Q_OBJECT
public:
qtColorWheel(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent* event) override;
int m_margin = 5;
};
struct Polar {
qreal radius;
qreal angle;
};
Polar cartesianToPolar(qreal x, qreal y)
{
qreal theta = atan2( x,y);
if (theta < 0) {
theta += (2 * M_PI);
}
qreal r = qSqrt((x * x) + (y * y));
Polar p;
p.angle = theta;
p.radius = r;
return p;
}
void qtColorWheel::paintEvent(QPaintEvent * event)
{
QPainter painter;
painter.begin(this);
QPen pen;
pen.setWidth(1);
auto min = qMin(width(), height()) - m_margin * 2;
auto center = QPointF(width() / 2.0, height() / 2.0);
auto offset = center - QPointF(min / 2.0, min / 2.0);
auto r = min / 2.0;
for (int w = 0; w <= min; w++) {
int a = w - r;
for (int h = 0; h <= min; h++) {
int b = r - h;
Polar p = cartesianToPolar(a, b);
if (p.radius <= r) {
qreal hue = p.angle / (2 * M_PI);
qreal sat = p.radius / r;
QColor color;
color.setHsvF(hue, sat, 1.0);
pen.setColor(color);
painter.setPen(pen);
painter.drawPoint(QPointF(w, h) + offset);
}
}
}
painter.end();
}
参考资料
https://stackoverflow.com/questions/59157309/drawing-an-hsv-color-wheel-in-qt-c