Mastering JavaFX 10
上QQ阅读APP看书,第一时间看更新

Dashed lines

By using the strokeDashArray method, you can make dashed lines. Each dash's size, and the spaces between them, are set in Stroke Dash Array. Each odd position is the dash length, and each even position is the length of the space before the next dash. Refer to the following code snippet:

// chapter2/strokes/DashExamples.java
Line line = new Line(50, 0, 250, 0);
line.setStrokeWidth(10);
line.setStroke(Color.DARKGRAY);
line.getStrokeDashArray().addAll(30.0, 15.0);

This method will give us the following line:

Note that the gaps between dashes look smaller than the 15 pixels we set. This is because, by default, StrokeLineCap is set to SQUARE, which means each gap ends with half of a square shape with a size of the half of stroke width. Here is a comparison of all three line caps:

And the last thing to note about dash is offset, which is a point in the dashed line that will be used as a start for drawing it:

line.setStrokeDashOffset(20);