使用 CSS/Code 创建复杂的 JavaFX 背景

Create complex JavaFX Background with CSS/Code

是否可以使用 CSS 或以编程方式在 JavaFX 中创建这样的背景,但在没有图像文件的情况下动态创建。

这是我要创建的图像:

你可以在Canvas, then turn it into an Image with the snapshot方法上自己画图:

Background createBackground() {
    double width = 200;
    double height = 200;

    Canvas canvas = new Canvas(width, height);
    GraphicsContext g = canvas.getGraphicsContext2D();

    double[] x;
    double[] y;

    g.setFill(Color.RED);

    // Left triangle
    x = new double[] { 0, 0, width / 2 };
    y = new double[] { 0, height, height / 2 };
    g.fillPolygon(x, y, x.length);

    // Right triangle
    x = new double[] { width, width, width / 2 };
    g.fillPolygon(x, y, x.length);

    g.setFill(Color.DARKGREEN);

    // Top triangle
    x = new double[] { 0, width, width / 2 };
    y = new double[] { 0, 0, height / 2 };
    g.fillPolygon(x, y, x.length);

    // Bottom triangle
    y = new double[] { height, height, height / 2 };
    g.fillPolygon(x, y, x.length);

    Image image = canvas.snapshot(null, null);

    return new Background(
        new BackgroundImage(image, null, null, null, null));
}