我想创建一个网格作为我的 JavaFX 应用程序的背景。我当前的解决方案是在画布上绘制一个矩形,从中创建一个图像图案并将其设置为填充。
Question:有没有更好的方法来解决这个问题,最好是通过CSS?
当前版本:
public class BackgroundGrid extends Application {
double gridSize = 20;
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new Group(), 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
scene.setFill(createGridPattern());
}
public ImagePattern createGridPattern() {
double w = gridSize;
double h = gridSize;
Canvas canvas = new Canvas(w, h);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setStroke(Color.BLACK);
gc.setFill(Color.LIGHTGRAY.deriveColor(1, 1, 1, 0.2));
gc.fillRect(0, 0, w, h);
gc.strokeRect(0, 0, w, h);
Image image = canvas.snapshot(new SnapshotParameters(), null);
ImagePattern pattern = new ImagePattern(image, 0, 0, w, h, false);
return pattern;
}
public static void main(String[] args) {
launch(args);
}
}
![enter image description here](https://i.stack.imgur.com/BclxI.png)
非常感谢!
编辑:为了获得清晰的网格线,只需使用
gc.strokeRect(0.5, 0.5, w, h);
我认为这在 CSS 中是不可能的,不是吗?
![enter image description here](https://i.stack.imgur.com/bXPEE.png)