0

I need to set color to view background and created Gradient view, here I'm getting only hsv color value and I need convert that rgb. converted rgb but its always gives me black color only. How can I change hsv color to rgb color code? its not applying to views in android. Please any suggestions?

public static String hsvToRgb(float H, float S, float V) {


    float R, G, B;

    H /= 360f;
    S /= 100f;
    V /= 100f;

    if (S == 0)
    {
        R = V * 255;
        G = V * 255;
        B = V * 255;
    } else {
        float var_h = H * 6;
        if (var_h == 6)
            var_h = 0; // H must be < 1
        int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
        // floor( var_h )
        float var_1 = V * (1 - S);
        float var_2 = V * (1 - S * (var_h - var_i));
        float var_3 = V * (1 - S * (1 - (var_h - var_i)));

        float var_r;
        float var_g;
        float var_b;
        if (var_i == 0) {
            var_r = V;
            var_g = var_3;
            var_b = var_1;
        } else if (var_i == 1) {
            var_r = var_2;
            var_g = V;
            var_b = var_1;
        } else if (var_i == 2) {
            var_r = var_1;
            var_g = V;
            var_b = var_3;
        } else if (var_i == 3) {
            var_r = var_1;
            var_g = var_2;
            var_b = V;
        } else if (var_i == 4) {
            var_r = var_3;
            var_g = var_1;
            var_b = V;
        } else {
            var_r = V;
            var_g = var_1;
            var_b = var_2;
        }

        R = var_r * 255; // RGB results from 0 to 255
        G = var_g * 255;
        B = var_b * 255;
    }

    String rs = Integer.toHexString((int) (R));
    String gs = Integer.toHexString((int) (G));
    String bs = Integer.toHexString((int) (B));

    if (rs.length() == 1)
        rs = "0" + rs;
    if (gs.length() == 1)
        gs = "0" + gs;
    if (bs.length() == 1)
        bs = "0" + bs;
    return "#" + rs + gs + bs;
}
Abhinav Gupta
  • 2,225
  • 1
  • 14
  • 30
Latha
  • 31
  • 4
  • 1
    [`Color.HSVToColor()`](http://developer.android.com/reference/android/graphics/Color.html#HSVToColor(float[])). If you really need the individual channel values, the `Color` class has methods for that, too. – Mike M. Mar 08 '18 at 07:39
  • Color.HSVToColor() but i need rgb color code – Latha Mar 08 '18 at 09:07
  • Are you sure? Your question seems to imply that you're just setting this color value on a `View`, in which case you can use the return from `Color.HSVToColor()` directly, without having to parse it. Anyway, if you do really need the hex string: https://stackoverflow.com/q/6539879. – Mike M. Mar 08 '18 at 09:11
  • 1
    yes, its working,tq – Latha Mar 09 '18 at 11:02

0 Answers0