Choose font color based on background color

This commit is contained in:
Jan Käberich 2021-10-25 20:56:27 +02:00
parent 1e1b7e0382
commit 61a081d3c6
3 changed files with 11 additions and 4 deletions

View File

@ -619,8 +619,7 @@ void Marker::updateSymbol()
p.setPen(traceColor);
p.setBrush(traceColor);
p.drawConvexPolygon(points, 3);
auto brightness = traceColor.redF() * 0.299 + traceColor.greenF() * 0.587 + traceColor.blueF() * 0.114;
p.setPen((brightness > 0.6) ? Qt::black : Qt::white);
p.setPen(Util::getFontColorFromBackground(traceColor));
p.drawText(QRectF(0,0,width, height*2.0/3.0), Qt::AlignCenter, QString::number(number) + suffix);
} else {
symbol = QPixmap(1,1);

View File

@ -7,6 +7,7 @@
#include <QDebug>
#include "unit.h"
#include "Marker/markermodel.h"
#include "Util/util.h"
std::set<TracePlot*> TracePlot::plots;
@ -176,7 +177,7 @@ void TracePlot::paintEvent(QPaintEvent *event)
path.addRoundedRect(usedLabelArea, borderRadius, borderRadius);
p.fillPath(path, t.first->color());
p.drawPath(path);
p.setPen(QColor(Qt::white));
p.setPen(Util::getFontColorFromBackground(t.first->color()));
p.drawText(textArea, 0, label);
p.setPen(t.first->color());
x += usedLabelArea.width()+labelMarginRight;
@ -206,7 +207,7 @@ void TracePlot::paintEvent(QPaintEvent *event)
p.fillPath(pathM, t.first->color());
p.drawPath(pathM);
p.setPen(QColor(Qt::white));
p.setPen(Util::getFontColorFromBackground(t.first->color()));
p.drawText(textArea, 0, label);
p.setPen(t.first->color());
p.drawText(textAreaConsumed.x()+textAreaConsumed.width(), textAreaConsumed.y(), textArea.width(), textArea.height(), 0, description);

View File

@ -5,6 +5,8 @@
#include <math.h>
#include <limits>
#include <QColor>
namespace Util {
template<typename T> T Scale(T value, T from_low, T from_high, T to_low, T to_high) {
value -= from_low;
@ -48,6 +50,11 @@ namespace Util {
static inline double SparamToQualityFactor(std::complex<double> d) {
return abs(d.imag()) / d.real();
}
// attempts to return a font color with good contrast against the given background color
static inline QColor getFontColorFromBackground(QColor q) {
auto brightness = q.redF() * 0.299 + q.greenF() * 0.587 + q.blueF() * 0.114;
return brightness > 0.6 ? Qt::black : Qt::white;
}
}
#endif // UTILH_H