在 JavaFX 上的按钮中加载 SVG 文件

2024-03-28

我在 Inkscape 中创建了一个 SVG 图像。我把它放在与我的班级相同的目录中。

有没有办法加载该图像并将其转换为 SVG 路径?

这背后的想法是获得该图像getClass().getResource("image.svg").toExternalForm()并将其转换为 SVGPathimageSVG.setContent()方法。之后我想将该 SVGPath 对象放入一个 Button 中button.setGraphic()方法。

我不想使用转码器或 BufferedImage 类。


随着SvgLoader由...提供https://github.com/afester/FranzXaver https://github.com/afester/FranzXaver,您可以简单地加载 SVG 文件作为 JavaFX 节点并将其设置在按钮上作为其图形:

...
    // load the svg file
    InputStream svgFile = 
          getClass().getResourceAsStream("/afester/javafx/examples/data/Ghostscript_Tiger.svg");
    SvgLoader loader = new SvgLoader();
    Group svgImage = loader.loadSvg(svgFile);

    // Scale the image and wrap it in a Group to make the button 
    // properly scale to the size of the image  
    svgImage.setScaleX(0.1);
    svgImage.setScaleY(0.1);
    Group graphic = new Group(svgImage);

    // create a button and set the graphics node
    Button button = new Button();
    button.setGraphic(graphic);

    // add the button to the scene and show the scene
    HBox layout = new HBox(button);
    HBox.setMargin(button, new Insets(10));
    Scene scene = new Scene(layout);
    primaryStage.setScene(scene);
    primaryStage.show();
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JavaFX 上的按钮中加载 SVG 文件 的相关文章