LibGfx: Correctly round values when computing the luminosity of a Color

Truncating the value is mathematically incorrect, this error made the
conversion to grayscale unstable. In other world, calling `to_grayscale`
on a gray value would return a different value. As an example,
`Color::from_string("#686868ff"sv).to_grayscale()` used to return
#676767ff.
This commit is contained in:
Lucas CHOLLET 2024-05-13 10:55:29 -04:00 committed by Jelle Raaijmakers
parent bd4f516e64
commit ff2c6cab55
Notes: sideshowbarker 2024-07-16 18:26:46 +09:00
3 changed files with 18 additions and 1 deletions

View file

@ -1,6 +1,7 @@
set(TEST_SOURCES
BenchmarkGfxPainter.cpp
BenchmarkJPEGLoader.cpp
TestColor.cpp
TestDeltaE.cpp
TestFontHandling.cpp
TestGfxBitmap.cpp

View file

@ -0,0 +1,16 @@
/*
* Copyright (c) 2024, Lucas Chollet <lucas.chollet@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGfx/Color.h>
#include <LibTest/TestCase.h>
TEST_CASE(color)
{
for (u16 i = 0; i < 256; ++i) {
auto const gray = Color(i, i, i);
EXPECT_EQ(gray, gray.to_grayscale());
}
}

View file

@ -316,7 +316,7 @@ public:
constexpr u8 luminosity() const
{
return (red() * 0.2126f + green() * 0.7152f + blue() * 0.0722f);
return round_to<u8>(red() * 0.2126f + green() * 0.7152f + blue() * 0.0722f);
}
constexpr float contrast_ratio(Color other)