1

Is it possible to draw a shape with open ends?

E.g.: Let's say I want to draw a tree, which roots are open. Is there a elegant way to let the ends open, without overdrawing the already drawed lines?

I could overdraw it with shapes, which are exactly as big as my openings and have the color of the background, but I don't think that is the elegant way and I don't find any option to let them open. Perhaps I'm just blind and I could make strokePolygon(...) in which not all points are linked, but I think that's neither the way to go.

Let's have a simple shape:

[ceate Scene and Stage, etc]
Canvas sc = new Canvas(x, y);
GraphicsContext gcCs = cs.getGraphicsContext2D();
gcCs.setStroke(Color.BLACK);
double counter = 0.0;

[calculate points, instantiate arrays, etc]

for (int i = 0; i < arrayX.length; i++)
{
    arrayX = shapeMidX + Math.cos(Math.toRadiants(counter * Math.PI)) * shapeSizeX / 2);
    arrayY = shapeMidY + Math.sin(Math.toRadiants(counter * Math.PI)) * shapeSizeY / 2);
}

gcCs.strokePolygon(arrayX, arrayY, arrayX.length);

[making other things]

stackPane.getChildren().add(sc);

I know that I could use .strokeOval(), but I wanted to have a example that is near of my own code.

I like to draw my shapes from the center.

P.S.: I wrote the for() { } out of my head, it could be that there's something wrong. I've got no Internet at home at the moment, so my answers could be taking a lot of time.

Thank you in advance.

Broken Dust
  • 19
  • 1
  • 3
  • Do your custom painting so shape is not closed. For example use [PolyLine](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polyline.html) : "The Polyline class is similar to the Polygon class, except that it is not automatically closed." – c0der Aug 16 '19 at 07:07
  • Wow, I have to be blind. Easy as f**k. Thank you. I'll try this. – Broken Dust Aug 16 '19 at 07:10

1 Answers1

1

You could draw individual lines using strokeLine and store the current position in variables allowing you to draw any combination of lines.

You could also construct a path instead which allows you to use moveTo instead of lineTo to "skip" a segment. This way you don't need to keep track of the previous position for continuous lines.

The following example draws every other line of a square this way:

@Override
public void start(Stage primaryStage) {
    Canvas canvas = new Canvas(400, 400);
    GraphicsContext gc = canvas.getGraphicsContext2D();

    gc.moveTo(100, 100);
    gc.lineTo(100, 300);
    gc.moveTo(300, 300);
    gc.lineTo(300, 100);
    // gc.moveTo(100, 100);

    gc.stroke();

    Scene scene = new Scene(new StackPane(canvas));
    primaryStage.setScene(scene);
    primaryStage.show();
}
fabian
  • 80,457
  • 12
  • 86
  • 114