Skip to content
Advertisement

Create smooth gradient with HSB in java

I’m trying to create a sorting algorithm visualiser in greenfoot java, with an array shown as a column graph. I want it to be colourful, so I’m using a colour gradient like shown in this video https://www.youtube.com/watch?v=qlvBsYyGIDo

This is the non-working code:

Pseudocode{
int[50] arr={1,2,3...}
for(int i:arr)
    rect.color=getColor(i,arr.length)
}

private static Color getColor(int value, int length){
    float h=((float)value/(float)length);//goes from 0-1
    System.out.println(value+" "+length+" "+h);
    java.awt.Color rgb=java.awt.Color.getHSBColor(h,255,255);
    int r=rgb.getRed();
    int g=rgb.getGreen();
    int b=rgb.getBlue();
    System.out.println(rgb+" "+r+" "+g+" "+b);
    return new Color(r,g,b);//greenfoot.Color, not java.awt.Color
}

But the colours it produces look like this: Screenshot of rectangles produced

How can I create a smoth gradient, from red->yellow->green->cyan->blue->magenta?

Advertisement

Answer

Thanks @Thomas. Turns out all three of the values for Color.getHSBColor() range from 0-1, and values higher than that produce ~undefined behaviour~.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement