1

Is there a simple way to draw a squiggly line across a path in JavaFX? Something like the horizontal line in enter image description here

(Source: https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Electron-positron-annihilation.svg/2000px-Electron-positron-annihilation.svg.png)

I know I can achieve this by breaking up the path to multiple parts, and drawing each with a cubic bezier curve, but I was hoping there was an easier way.

hotzst
  • 7,238
  • 9
  • 41
  • 64
Itai
  • 6,641
  • 6
  • 27
  • 51
  • You've got a svg; It would be easy to use `SVGPath` to create the path (Which of course uses cubic Bézier curves...). The only way to do this not using Bézier curves that comes to my mind is using the `DisplacementMap` effect on a `Line` but this results in horrible quality and isn't really easier. Using Bézier curves isn't that complicated. It can be done with approx 40 LOC for any given start/end point / wave height / wave length. – fabian Jan 27 '16 at 18:44
  • Yes, I just thought maybe there is a built-in way. Take dashes for example - you could easily accomplish a dashed line with interchanging `MoveTo` and `LineTo`, but JavaFX provides a built in which is much simpler to use. – Itai Jan 27 '16 at 19:15

1 Answers1

1

Wave line with Path

In this approach wavyPath method will return a Path object with nested CubicCurbeTo path elements . Where length is the length of the line in x axis , subDivisions are the amount of curves and controlY is the height in y axis . In this case the method will make a path of 200 pixels length with four curves and 40 pixels amplitude (80 pixels height).

Docs of Path and CubicCurveTo (javafx 19)

This is a single class javafx app you can try

App.java

public class App extends Application {

    @Override
    public void start(Stage stage) {

        var scene = new Scene(new StackPane(wavyPath(200, 4, 40)), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

    private Path wavyPath(double length, int subdivisions, int controlY) {
        var path = new Path(new MoveTo(0, 0));
        double curveLengthX = length / subdivisions;
        double controlX = curveLengthX * 0.5;

        for (int i = 0; i < subdivisions; i++) {

            var curve = 
                    new CubicCurveTo((curveLengthX * i) + controlX, -controlY, 
                            (curveLengthX * i) + controlX, controlY, curveLengthX * (i + 1), 0);

            System.out.println(curveLengthX * (1 + i));
            path.getElements().add(curve);
        }
        path.setStroke(Color.PURPLE);
        path.setStrokeWidth(3);
        return path;

    }

}

Result

wave line javafx

Giovanni Contreras
  • 2,345
  • 1
  • 13
  • 22