Rol*_*and 1 css background javafx
我想创建一个网格作为JavaFX应用程序的背景。我当前的解决方案是在画布上绘制一个矩形,从该矩形创建图像图案并将其设置为填充。
问题:是否有更好的方法(最好通过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);
}
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你!
编辑:为了获得清晰的网格线,只需使用
gc.strokeRect(0.5, 0.5, w, h);
Run Code Online (Sandbox Code Playgroud)
我认为这在CSS中不可行,不是吗?

您也可以使用CSS。这就是您所需要的:
.root {
-fx-background-color: #D3D3D333,
linear-gradient(from 0.5px 0.0px to 10.5px 0.0px, repeat, black 5%, transparent 5%),
linear-gradient(from 0.0px 0.5px to 0.0px 10.5px, repeat, black 5%, transparent 5%);
}
Run Code Online (Sandbox Code Playgroud)

从0px设置为10px时,0.5px偏移量解决了一些错误行为,并且某些行用两个像素而不是一个像素渲染:
