I wanted to write a function which could check if color is close to a background color.
For this i make use of the HSL color scheme, let me explain that a bit; HSL colors are defined as Hue Saturation and lightness. In short Hue tells you which color of the rainbow is used and its in the range 0 to 360. And its on the Hue that i would like check.
So Saturation how strong the color is, like pure or mixed with grey
or Lightness which speaks for itself are not compared. I only want to check for Hue.
At first i 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 this is wrong. Because HSL is like the image below you see in there the colors are as a circle, so starting at red 0 and it is red again at 360.
So a Hue value of 358 and 4 are close together, the above function wouldn’t reflect that.
(Saturation goes to the center 0..100
lightens 0..100 is like going up or down
and Hue is from 0 to 360 degrees around. )

I could rewrite a function with a large if then construction, so that for example if the background where red 5 and the allowed difference is 20 then mycolor would be in range if it is < 5+20 or > (360-(5-20)) .. so making a special construction if the Hue difference would be crossing the 0 or 360 limits.
Well that would work, but then i wondered might it be possible to replace such “if then” construction with a modulo calculation in a single line ?, it keeps me wondering still
As modulo computations can be used to check within a border and if its over the border of 360 it would be red again close to zero,
well i think so, such line might also contain some AND or OR and subtractions or ABS functions..might it be possible to write it in one comparison line ?
What you need to do is ensure that the values you are comparing are as close as they can be. For instance, if
background = 358, andmycolor = 4, then they could be made closer by subtracting360frombackground, which doesn’t change the effective value. They need to be made closer as long as the difference >180.With these transformations, your original logic should then be correct (the
ifis unnecessary):Edit: I have found a simpler expression that seems to be correct.