diff --git a/include/wx/colour.h b/include/wx/colour.h index e9a13ef95e..87253462b5 100644 --- a/include/wx/colour.h +++ b/include/wx/colour.h @@ -154,6 +154,10 @@ public: bool Ok() const { return IsOk(); } #endif + // Return the perceived brightness of the colour, with 0 for black and 1 + // for white. + double GetLuminance() const; + // manipulation // ------------ diff --git a/interface/wx/colour.h b/interface/wx/colour.h index a3d4ef7afa..7981e0208a 100644 --- a/interface/wx/colour.h +++ b/interface/wx/colour.h @@ -158,6 +158,19 @@ public: wxUint32 GetRGBA() const; //@} + /** + Return the perceived brightness of the colour. + + This value is computed using the simple @code 0.299*R + 0.587*G + + 0.114*B @endcode formula with the coefficients taken from the RGB to + YIQ conversion formula and @c R, @c G and @c B being the values of the + corresponding colour channels normalized to 0..1 range, so that the + return value is 0 for black and 1 for white. + + @since 3.1.3 + */ + double GetLuminance() const; + /** Returns a pixel value which is platform-dependent. On Windows, a COLORREF is returned. diff --git a/src/common/colourcmn.cpp b/src/common/colourcmn.cpp index 49b7c0c6b0..0ae45ceac8 100644 --- a/src/common/colourcmn.cpp +++ b/src/common/colourcmn.cpp @@ -268,6 +268,11 @@ wxString wxColourBase::GetAsString(long flags) const return colName; } +double wxColourBase::GetLuminance() const +{ + return (0.299*Red() + 0.587*Green() + 0.114*Blue()) / 255.0; +} + // static void wxColourBase::MakeMono(unsigned char* r, unsigned char* g, unsigned char* b, bool on) diff --git a/tests/graphics/colour.cpp b/tests/graphics/colour.cpp index fbfa96870a..bde3b17803 100644 --- a/tests/graphics/colour.cpp +++ b/tests/graphics/colour.cpp @@ -115,3 +115,10 @@ void ColourTestCase::FromString() CPPUNIT_ASSERT( !wxFromString("rgba(1, 2, 3.456, foo)", &col) ); } +TEST_CASE("wxColour::GetLuminance", "[colour][luminance]") +{ + CHECK( wxBLACK->GetLuminance() == Approx(0.0) ); + CHECK( wxWHITE->GetLuminance() == Approx(1.0) ); + CHECK( wxRED->GetLuminance() > 0 ); + CHECK( wxRED->GetLuminance() < 1 ); +}