如何创建背景网格 [英] How to create a background grid

查看:163
本文介绍了如何创建背景网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个网格作为我的JavaFX应用程序的背景。我目前的解决方案是在画布上绘制一个矩形,从中创建一个图像模式并将其设置为填充。

I'd like to create a grid as a background for my JavaFX application. My current solution is to paint a rectangle on a canvas, create an image pattern from it and set it as fill.

问题:是否存在一个更好的方法来解决这个问题,最好是通过CSS吗?

Question: Is there a better way to approach this, preferrably via 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);
    }
}

非常感谢!

编辑:为了获得清晰的网格线,只需使用

in order to get sharp grid lines, just use

gc.strokeRect(0.5, 0.5, w, h);

我认为CSS不可行,不是吗?

I think that wouldn't be doable in CSS, isn't it?

推荐答案

你也可以用CSS来做。这就是你所需要的:

You can do it with CSS too. This is all you need:

.root {
    -fx-background-color: #D3D3D333,
        linear-gradient(from 0.5px 0px to 10.5px 0px, repeat, black 5%, transparent 5%),
        linear-gradient(from 0px 0.5px to 0px 10.5px, repeat, black 5%, transparent 5%);
}

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

The 0.5px offset solves some buggy behavior when set from 0px to 10px, and some lines are rendered with two pixels instead of one:

这篇关于如何创建背景网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆