From f274f04e35c1927a02c6c5bb3280be0d9ae13a7a Mon Sep 17 00:00:00 2001 From: MacDue Date: Mon, 28 Nov 2022 22:27:38 +0000 Subject: [PATCH] LibGfx: Handle alpha in color distance This gives a slightly more reasonable result when comparing different colors with low alpha values. For example comparing white with alpha 100 to transparent: Before distance: 0.78 After distance: 0.07 (Where distance is between 0 and 1) The result is unchanged for comparing colors without alpha values. --- Userland/Libraries/LibGfx/Color.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Userland/Libraries/LibGfx/Color.h b/Userland/Libraries/LibGfx/Color.h index c63834358d..0cab5cfe5e 100644 --- a/Userland/Libraries/LibGfx/Color.h +++ b/Userland/Libraries/LibGfx/Color.h @@ -257,11 +257,12 @@ public: constexpr float distance_squared_to(Color const& other) const { - int a = other.red() - red(); - int b = other.green() - green(); - int c = other.blue() - blue(); - int d = other.alpha() - alpha(); - return (a * a + b * b + c * c + d * d) / (4.0f * 255.0f * 255.0f); + int delta_red = other.red() - red(); + int delta_green = other.green() - green(); + int delta_blue = other.blue() - blue(); + int delta_alpha = other.alpha() - alpha(); + auto rgb_distance = (delta_red * delta_red + delta_green * delta_green + delta_blue * delta_blue) / (3.0f * 255 * 255); + return delta_alpha * delta_alpha / (2.0f * 255 * 255) + rgb_distance * alpha() * other.alpha() / (255 * 255); } constexpr u8 luminosity() const