Boolean function to find if HSL based color is close to another color
I wanted to write a function that could check if the background color is close.
For this I am using the HSL color scheme, let me explain it a bit; HSL colors are defined as the saturation and lightness of the hue. In short, Hue is telling you what color of the rainbow is used, and it ranges from 0 to 360. And its on the hue I would like to test.
So saturation, how strong a color is, like pure or mixed with gray, or Lightness that speaks for itself, is not comparable. I just want to check Hugh. I first wrote a Near function like this:
Private boolean Near(int background, int mycolor, int difference)
{
if(math.abs( background - mycolor)<difference){return true;}else{return false}
}
Later I realized it was wrong. Since the HSL is similar to the image below, you see the colors there as a circle, so start at red 0 and red again at 360. So the hue value 358 and 4 are close together, the above function does not reflect that.
(Saturation goes to the center 0..100 glows 0..100 is like moving up or down and hue from 0 to 360 degrees around.)
I could rewrite the function with a large if then construct, so that, for example, if the background where red is 5 and the allowed difference is 20, then it mycolor
will be in the range if it is <5 + 20 or> (360- (5- 20)) .. therefore creating a special design if the hue difference will cross the 0 or 360 limits.
It's good that it works, but then I wondered if it was possible to replace such an "if then" with a modular computation in one line? 360 will be red again close to zero,
Well, I think so, such a string could also contain some AND or OR and subtraction or ABS functions. Is it possible to write this in one comparison line?
source to share
What you need to do is make sure that the values you are comparing are as close as possible. For example, if background = 358
and mycolor = 4
, then they could be brought closer by subtracting 360
from background
, which does not change the effective value. They need to be brought closer as long as the difference is> 180
.
if (mycolor - background > 180) mycolor -= 360;
if (background - mycolor > 180) background -= 360;
With these conversions, your original logic should be correct ( if
not required):
return Math.Abs(background - mycolor) < difference;
Edit . I found a simpler expression that seems to be correct.
return Math.Abs(background - mycolor) % (361 - difference) < difference;
source to share