如何从渐变中获取颜色

How to get color from a gradient

我有一个渐变,e。 G。绿色到红色,范围从 0 到 100。我需要从该渐变中查找任何给定值的颜色。目前我正在 canvas 上画一条线,填充它,拍摄快照并使用 pixelreader 获取颜色。有谁知道更好的方法?这对我来说似乎有点矫枉过正。

代码的简单版本:

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);
}

非常感谢!

你可以自己插值颜色:

Color imageColor = Color.GREEN.interpolate(Color.RED, value / 100.0);