File indexing completed on 2024-04-28 03:41:52

0001 // SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: LGPL-2.0-or-later
0003 
0004 #include "colorutils.h"
0005 
0006 #include <QGuiApplication>
0007 #include <QPalette>
0008 
0009 QColor ColorUtils::tintWithAlpha(const QColor &targetColor, const QColor &tintColor, double alpha)
0010 {
0011     qreal tintAlpha = tintColor.alphaF() * alpha;
0012     qreal inverseAlpha = 1.0 - tintAlpha;
0013 
0014     if (qFuzzyCompare(tintAlpha, 1.0)) {
0015         return tintColor;
0016     } else if (qFuzzyIsNull(tintAlpha)) {
0017         return targetColor;
0018     }
0019 
0020     return QColor::fromRgbF(tintColor.redF() * tintAlpha + targetColor.redF() * inverseAlpha,
0021                             tintColor.greenF() * tintAlpha + targetColor.greenF() * inverseAlpha,
0022                             tintColor.blueF() * tintAlpha + targetColor.blueF() * inverseAlpha,
0023                             tintAlpha + inverseAlpha * targetColor.alphaF());
0024 }
0025 
0026 QColor ColorUtils::contrastColor(const QColor &color)
0027 {
0028     const auto lightness = static_cast<QGuiApplication *>(QGuiApplication::instance())->palette().color(QPalette::Active, QPalette::Window).lightnessF();
0029     // https://github.com/quotient-im/libQuotient/wiki/User-color-coding-standard-draft-proposal
0030     return QColor::fromHslF(color.hsvHueF(), 1, -0.7 * lightness + 0.9, 1);
0031 }