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!