【发布时间】:2015-05-06 09:15:54
【问题描述】:
我想创建一个网格作为我的 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);
}
}
非常感谢!
编辑:为了获得清晰的网格线,只需使用
gc.strokeRect(0.5, 0.5, w, h);
我认为这在 CSS 中是不可行的,不是吗?
【问题讨论】:
-
谢谢,我已经看到了。我的意思是如果可以只用 css 做所有事情,而不是如何应用自定义 css。顺便说一句,你认为什么更快?用图案的解决方案还是用线条绘制的解决方案?我不确定,因为我不知道内部发生了什么。
-
我不知道哪个更快,但如果我不得不猜测,我会说这取决于你调整网格的大小。
标签: css background javafx