简体   繁体   English

有什么方法可以在JavaFX中构建路径渐变?

[英]Is there any way to build a path gradient in JavaFX?

I need to use path gradients (vary the stroke color along a path), but currently couldn't find a way to do it with the current JavaFX API. 我需要使用路径渐变(沿路径改变笔触颜色),但是目前找不到使用当前JavaFX API的方法。 Note that this is different than applying a linear gradient to a path element. 请注意,这与将线性渐变应用于路径元素不同。 This may seem to work for straight line segments, but fails in some arc configurations and multiple connected path elements. 这似乎适用于直线段,但在某些弧形配置和多个连接的路径元素中无效。

Would someone offer any suggestions for an approach to this problem? 有人会提供解决此问题的建议吗?

You can try the following approach: 您可以尝试以下方法:

@Override
public void start(Stage primaryStage) {
    Group root = new Group();

    // CREATE CANVAS
    final Canvas canvas = new Canvas(300, 250);
    // GET GRAPHICS CONTEXT
    final GraphicsContext gc = canvas.getGraphicsContext2D();


    // DRAW THE SHAPE (LINE)
    gc.beginPath();
    gc.moveTo(50, 50);     //Begin
    gc.lineTo(150, 200);   //End
    gc.closePath();

    // CREATE THE LINEAR EFFECT
    LinearGradient lg = new LinearGradient(0, 0, 1, 1, true,
            CycleMethod.REFLECT, new Stop(0.0, Color.RED), 
                                 new Stop(0.5, Color.GREEN),
                                 new Stop(1.0, Color.BLUE));
    // SET & STROKE WITH LINEAR
    gc.setLineWidth(20);
    gc.setStroke(lg);
    gc.stroke();


    //ADD CANVAS NODE TO ROOT
    root.getChildren().add(canvas);
    primaryStage.setScene(new Scene(root));
    primaryStage.show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM