1

Is there a way to create a curve in JavaFX with a varying stroke width? For example, starting at 10 point and end at 1 point.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
melkhaldi
  • 899
  • 2
  • 19
  • 40

1 Answers1

1

You can't vary the stroke width.

You can simulate this behavior though, by creating a path which layers multiple curves, which start at different starting positions but converge to a single point.

path

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;

import java.util.Random;

public class DividedPath extends Application {

    private static final double WIDTH = 400, HEIGHT = 400;
    private static final Random random = new Random(42);

    @Override public void start(Stage stage) {
        CubicCurve curve = randomCurve(WIDTH, HEIGHT);

        Path path = new Path();
        for (int i = -5; i <= +5; i++) {
            path.getElements().addAll(
                    new MoveTo(curve.getStartX() + i, curve.getStartY()),
                    new CubicCurveTo(
                            curve.getControlX1(),
                            curve.getControlY1(),
                            curve.getControlX2(),
                            curve.getControlY2(),
                            curve.getEndX(),
                            curve.getEndY()
                    )
            );
        }
        path.setStroke(Color.FORESTGREEN);

        Group root = new Group();
        curve.setFill(null);
        root.getChildren().addAll(
                path,
                curve
        );

        Scene scene = new Scene(
                root,
                WIDTH, HEIGHT,
                Color.rgb(35,39,50)
        );

        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    private CubicCurve randomCurve(double mx, double my) {
        return new CubicCurve(
                random.nextDouble() * mx,
                random.nextDouble() * my,
                random.nextDouble() * mx,
                random.nextDouble() * my,
                random.nextDouble() * mx,
                random.nextDouble() * my,
                random.nextDouble() * mx,
                random.nextDouble() * my
        );
    }
}
jewelsea
  • 150,031
  • 14
  • 366
  • 406