我有一个渐变,e。 G。绿色到红色,范围从0到100.我需要为任何给定值查找该渐变的颜色。目前我正在画布上绘制一条线,填充它,拍摄快照并使用像素阅读器来获取颜色。有谁知道更好的方法?这对我来说似乎有点过分了。
代码的简单版本:
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);
}
非常感谢!
答案 0 :(得分:4)
您可以自己插入颜色:
Color imageColor = Color.GREEN.interpolate(Color.RED, value / 100.0);