0

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?

Amber Cahill
  • 106
  • 8
  • 1
    You might want to read the JavaDocs more carefully, e.g. the one on Color.getHSBColor states: "The s and b components should befloating-point values between zero and one" - so passing 255 is wrong already. Try `getHSBColor(h, 1.0f, 1.0f)` instead. – Thomas Apr 12 '21 at 06:18

1 Answers1

0

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

Amber Cahill
  • 106
  • 8