File: gradient_helper.hpp

package info (click to toggle)
qt-color-widgets 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,088 kB
  • sloc: cpp: 7,426; sh: 236; makefile: 14
file content (83 lines) | stat: -rw-r--r-- 2,216 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * SPDX-FileCopyrightText: 2013-2020 Mattia Basaglia
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#ifndef GRADIENT_HELPER_HPP
#define GRADIENT_HELPER_HPP

#include "colorwidgets_global.hpp"

#include <QGradient>

namespace color_widgets {

inline QColor blendColors(const QColor& a, const QColor& b, qreal ratio)
{
    return QColor::fromRgbF(
        a.redF()   * (1-ratio) + b.redF()   * ratio,
        a.greenF() * (1-ratio) + b.greenF() * ratio,
        a.blueF()  * (1-ratio) + b.blueF()  * ratio,
        a.alphaF() * (1-ratio) + b.alphaF() * ratio
    );
}


/**
 * \brief Get an insertion point in the gradient
 * \param gradient  Gradient stops to look into (must be properly set up)
 * \param factor    Value in [0, 1] to get the color for
 * \return A pair whose first element is the index to insert the new value at, and a GradientStop
 */
inline QPair<int, QGradientStop> Q_DECL_EXPORT gradientBlendedColorInsert(const QGradientStops& gradient, qreal factor)
{
    if ( gradient.empty() )
        return {0, {0, QColor()}};

    if ( gradient.size() == 1 || factor <= 0 )
        return {0, gradient.front()};

    int i = 0;
    QGradientStop s1;
    for ( auto s2 : gradient )
    {
        if ( factor < s2.first )
        {
            qreal ratio = (factor - s1.first) / (s2.first - s1.first);
            return {i, {factor, blendColors(s1.second, s2.second, ratio)}};
        }
        s1 = s2;
        ++i;
    }

    return {gradient.size(), gradient.back()};
}

/**
 * \brief Returns a color in the gradient
 * \param gradient  Gradient stops to look into (must be properly set up)
 * \param factor    Value in [0, 1] to get the color for
 */
inline QColor Q_DECL_EXPORT gradientBlendedColor(const QGradientStops& gradient, qreal factor)
{
    return gradientBlendedColorInsert(gradient, factor).second.second;
}

/**
 * \brief Returns a color in the gradient
 * \param gradient  Gradient to look into
 * \param factor    Value in [0, 1] to get the color for
 */
inline QColor Q_DECL_EXPORT gradientBlendedColor(const QGradient& gradient, qreal factor)
{
    return gradientBlendedColor(gradient.stops(), factor);
}

} // namespace color_widgets




#endif // GRADIENT_HELPER_HPP