Search code examples
javaandroidcolorsinternal

android Color class - strange behavior, internal rounding error?


i have got a simple color int like 0x8833aacc
if i now use Color.colorToHSV to create HSV value of it,
and then use Color.HSVToColor to get the int back, it is slightly different!
the red value decreases by 1

but it does this not everytime, e.g. when using 0x8830aacc everythings ok, why?
my example code to show this:

final float[] current_hsv = new float[3];
float current_alpha = 1.0f;

private int GetColor()
{
    return Color.HSVToColor((int)(current_alpha * 255.0f), current_hsv);
}

private void SetColor(int color)
{
    Color.colorToHSV(color, current_hsv);
    current_alpha = (float)Color.alpha(color) / 255.0f;
}

private void Test()
{
    int color = 0x8833aacc;
    SetColor(color);
    int g = GetColor();

    //convert to hex, you'll see the red value decreased by 1!!!
    Log.i("Test", "color: " + String.format("%08x", color) + " got color: " + String.format("%08x", g));
}

how can i fix that?


Solution

  • fixed it myself:
    there is defenitely a bug inside androids Color.colorToHSV or Color.HSVToColor.
    im now using oracles HSBToRGB and RGBToHSB implementations,
    and they dont have this issue.

    (for those who don't know: HSB is [hue] [saturation] [brightness]
    and [brightness] is the same as [value] from HSV - so there is no difference)
    now everything is working fine :)