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

时间:2015-11-09 13:45:32

标签: java javafx javafx-8 javafx-css

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

这是我要创建的图片:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以自己在Canvas上绘制图像,然后使用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));
}