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

Paths

Path is a metashape. You can merge any combination of shape-like PathElement objects into one Path and use the result as a single shape.

The following PathElement classes are supported in JavaFX 9:

ArcTo, ClosePath, CubicCurveTo, HLineTo, LineTo, MoveTo, QuadCurveTo, VLineTo

Their parameters mostly resemble corresponding shapes, except ClosePath, which is a marker of the path end.

Here is an example:

Take a look at the following code snippet:

// chapter2/shapes/PathDemo.java
ArcTo arcTo = new ArcTo();
arcTo.setRadiusX(250);
arcTo.setRadiusY(90);
arcTo.setX(50);
arcTo.setY(100);
arcTo.setSweepFlag(true);

Path path = new Path(
new MoveTo(0, 0),
new HLineTo(50),
arcTo, // ArcTo is set separately due to its complexity
new VLineTo(150),
new HLineTo(0),
new ClosePath()
);

SVGPath is similar to Path, but it uses text commands instead of code elements. These commands are not specific to JavaFX, they are part of Scalable Vector Graphics specification. So, you can reuse existing SVG shapes in JavaFX:

SVGPath svgPath = new SVGPath();
svgPath.setContent("M0,0 H50 A250,90 0 0,1 50,100 V150 H0 Z");
// SVG notation help:
// M - move, H - horizontal line, A - arc
// V - vertical line, Z - close path
svgPath.setFill(Color.DARKGREY);

This is the result:

By comparing Path and SVGPath, you can see a certain resemblance. It explains an odd, at first, choice of PathElement objects—they were mimicked after SVG ones.