2

I have a gradient, e. g. green to red which ranges from 0 to 100. I need to lookup a color out of that gradient for any given value. Currently I'm painting a line on a canvas, fill it, take a snapshot and use a pixelreader to get the color. Does anyone know a better way? It seems like overkill to me.

A simple version of the code:

private Color getColor( double value) {

    Canvas canvas = new Canvas(100, 1);
    GraphicsContext gc = canvas.getGraphicsContext2D();

    Stop[] stops = new Stop[] { new Stop(0, Color.GREEN),  new Stop(1, Color.RED)};

    LinearGradient linearGradient = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
    gc.setFill(linearGradient);
    gc.rect( 0, 0, canvas.getWidth(), canvas.getHeight());
    gc.fill();

    WritableImage image = new WritableImage((int) canvas.getWidth(), (int) canvas.getHeight());
    image = canvas.snapshot(null, image);

    PixelReader imageReader = image.getPixelReader();
    Color imageColor = imageReader.getColor( (int) value, 0);
}

Thank you very much!

Roland
  • 18,114
  • 12
  • 62
  • 93
  • This is similar to the StackOverflow question: [Applying gradient coloring with one parameter](http://stackoverflow.com/questions/13455099/applying-gradient-coloring-with-one-parameter) and the Oracle JavaFX forum question: [Using a CSS LinearGradient to create a Color - LookUpTable](https://community.oracle.com/thread/2544108) – jewelsea Mar 10 '15 at 22:37

1 Answers1

5

You can interpolate the color yourself:

Color imageColor = Color.GREEN.interpolate(Color.RED, value / 100.0);
samgak
  • 23,944
  • 4
  • 60
  • 82