Manipulating an SVGPath in JavaFX

2019-08-16 06:17发布

Is there a way to examine/manipulate the elements of an SVGPath? Since it is not derived from Path (It is a direct subclass of Shape), I can't get the PathElements via Path's getElements method.

(In essence, I'd like to use SVGPath as an SVG path parser, instead of having to include Apache Batik or writing my own).

标签: java svg javafx
1条回答
做个烂人
2楼-- · 2019-08-16 07:13

There is an easy way to convert SVGPath to Path without any third party dependency, based precisely in their common superclass Shape's method substract. The result of a substract operation can be downcasted to Path:

Path path = (Path) (Shape.subtract(svgPath, new Rectangle(0, 0)));

So given a certain SVGPath, like one of the segments of the SVG logo:

SVGPath svgPath = new SVGPath();
svgPath.setContent("M-84.1487,-15.8513 a22.4171,22.4171 0 1 0 0,31.7026 h168.2974 a22.4171,22.4171 0 1 0 0,-31.7026 Z");
svgPath.setFill(Color.TRANSPARENT);
svgPath.setStroke(Color.RED);

you can easily get the Path with all the different PathElement elements:

Path path = (Path)(Shape.subtract(svgPath, new Rectangle(0, 0)));
path.setFill(Color.TRANSPARENT);
path.setStroke(Color.BLACK);

and print the elements:

path.getElements().forEach(System.out::println);

with the following result:

MoveTo[x=-99.99996948242188, y=-22.91710090637207]
CubicCurveTo[x=-116.20481872558594, y=-16.20482063293457, controlX1=-105.8649673461914, controlY1=-22.91710090637207, controlX2=-111.72997283935547, controlY2=-20.67967414855957]
...
LineTo[x=83.94287872314453, y=16.351303100585938]
...
ClosePath

You can now manipulate the Path or any of its elements, but there is no easy way of getting a new SVGPath back from the Path.

You can find a ShapeConverter utility in the JFXtras project. With it you can generate the SVGPath again:

SVGPath newSVGPath = ShapeConverter.shapeToSvgPath(path); 
查看更多
登录 后发表回答