@@ -11,43 +11,50 @@ class ColorUtils : public QObject {
1111 QML_SINGLETON
1212public:
1313 explicit ColorUtils (QObject* parent = nullptr );
14- static ColorUtils* create (QQmlEngine* qmlEngine, QJSEngine* jsEngine) {
15- Q_UNUSED (jsEngine)
16- return new ColorUtils (qmlEngine);
17- }
14+
15+ struct HSLA {
16+ HSLA () = default ;
17+ HSLA (float h, float s, float l, float a = 1.0 )
18+ : h(h)
19+ , s(s)
20+ , l(l)
21+ , a(a) {
22+ }
23+ explicit HSLA (QColor c) {
24+ c.getHslF (&h, &s, &l, &a);
25+ }
26+ QColor toColor () const {
27+ return QColor::fromHslF (h, s, l, a);
28+ }
29+ float h = 0 .0F ;
30+ float s = 0 .0F ;
31+ float l = 0 .0F ;
32+ float a = 0 .0F ;
33+ };
34+
1835
1936 Q_INVOKABLE static QColor mixColors (QColor a, QColor b, float ratio) {
2037 return QColor::fromRgbF (
21- a.redF () * ratio + b.redF () * (1 .0f - ratio), a.greenF () * ratio + b.greenF () * (1 .0f - ratio),
22- a.blueF () * ratio + b.blueF () * (1 .0f - ratio), a.alphaF () * ratio + b.alphaF () * (1 .0f - ratio)
38+ ( a.redF () * ratio) + ( b.redF () * (1 .0F - ratio)), ( a.greenF () * ratio) + ( b.greenF () * (1 .0F - ratio) ),
39+ ( a.blueF () * ratio) + ( b.blueF () * (1 .0F - ratio)), ( a.alphaF () * ratio) + ( b.alphaF () * (1 .0F - ratio) )
2340 );
2441 }
2542 Q_INVOKABLE static QColor setAlpha (QColor c, float alpha) {
26- QColor modified = c;
27- modified.setAlphaF (alpha);
28- return modified;
43+ c.setAlphaF (alpha);
44+ return c;
2945 }
3046 Q_INVOKABLE static QColor darken (QColor c, float ratio) {
31- qreal newLightness = qMax (0 .0f , qMin (1 .0f , c.lightnessF () / ratio));
32- return QColor::fromHslF (c.hslHueF (), c.hslSaturationF (), newLightness);
47+ HSLA hsla (c);
48+ hsla.l = std::clamp (hsla.l / ratio, 0 .0F , 1 .0F );
49+ return hsla.toColor ();
3350 }
3451 Q_INVOKABLE static QColor lighten (QColor c, float ratio) {
35- return darken (c, 1 .0f / ratio);
52+ return darken (c, 1 .0F / ratio);
3653 }
3754 Q_INVOKABLE static QColor saturate (QColor c, float ratio) {
38- float h = c.hslHueF ();
39- float s = c.hslSaturationF ();
40- float l = c.lightnessF ();
41- float a = c.alphaF ();
42-
43- s *= ratio;
44- if (s > 1.0 ) {
45- s = 1.0 ;
46- }
47- if (s < 0.0 ) {
48- s = 0.0 ;
49- }
50- return QColor::fromHslF (h, s, l, a);
55+ HSLA hsla (c);
56+ hsla.s = std::clamp (hsla.s * ratio, 0 .0F , 1 .0F );
57+ return hsla.toColor ();
5158 }
5259 // If used with light mode, this will make things lighter and vice versa.
5360 Q_INVOKABLE static QColor daytimeModeAdjust (QColor c, float ratio);
0 commit comments