util.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #pragma once
  2. #include <QColor>
  3. namespace util {
  4. inline double linearInterpolate(double first, double second, double alpha) {
  5. return first * (1.0 - alpha) + second * alpha;
  6. }
  7. inline double inverseLinearInterpolation(double min, double max, double value) {
  8. if (max - min == 0) return max;
  9. else return (value - min) / (max - min);
  10. }
  11. inline QColor interpolateHSL(QColor& first, QColor& second, double alpha)
  12. {
  13. double firstH, firstS, firstL;
  14. double secondH, secondS, secondL;
  15. first.getHslF(&firstH, &firstS, &firstL);
  16. second.getHslF(&secondH, &secondS, &secondL);
  17. if (firstH == -1) {
  18. firstH = (secondH != -1) ? secondH : 0;
  19. }
  20. if (secondH == -1) {
  21. secondH = (firstH != -1) ? firstH : 0;
  22. }
  23. const double h = util::linearInterpolate(firstH, secondH, alpha);
  24. const double s = util::linearInterpolate(firstS, secondS, alpha);
  25. const double l = util::linearInterpolate(firstL, secondL, alpha);
  26. return QColor::fromHslF(h, s, l);
  27. }
  28. inline QColor interpolateRGB(QColor& first, QColor& second, double alpha)
  29. {
  30. const double r = util::linearInterpolate(first.redF(), second.redF(), alpha);
  31. const double g = util::linearInterpolate(first.greenF(), second.greenF(), alpha);
  32. const double b = util::linearInterpolate(first.blueF(), second.blueF(), alpha);
  33. return QColor::fromRgbF(r, g, b);
  34. }
  35. }