提问者:小点点

Javafx Canvas rect不绘制


我做了一些非常基本的事情,我只是不知道哪里出了问题。

我试着在画布上画一个网格,看起来很直,但是我的矩形轮廓有问题。他们根本没有画出来!!

    canvas.getGraphicsContext2D().setFill(Color.YELLOW);
    canvas.getGraphicsContext2D().setStroke(Color.BLACK);
    canvas.getGraphicsContext2D().setLineWidth(2d);

    for (int dy = 0; dy < height; dy ++){
        for (int dx = 0; dx < width; dx ++){
            canvas.getGraphicsContext2D().setFill(new Color( random.nextDouble(), random.nextDouble(), random.nextDouble() ,1));
            canvas.getGraphicsContext2D().fillRect(dx*32,dy*32,32,32);
            canvas.getGraphicsContext2D().rect(dx*32,dy*32,32,32);
        }
    }

结果很有趣,因为它确实画了,但不是轮廓…

没那么难吧?我错过了什么?


共1个答案

匿名用户

您只需将元素附加到路径中,但您永远不会对其做任何事情。您需要使用路径调用一些方法。在您的情况下,您需要调用stro

@Override
public void start(Stage stage) throws IOException {
    Canvas canvas = new Canvas(512, 512);
    Scene scene = new Scene(new Pane(canvas));

    Random random = new Random();
    final int height = 16;
    final int width = 16;

    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.setStroke(Color.BLACK);
    gc.setLineWidth(2d);

    for (int dy = 0; dy < height; dy++) {
        for (int dx = 0; dx < width; dx++) {
            gc.setFill(new Color(random.nextDouble(), random.nextDouble(), random.nextDouble(), 1));
            gc.fillRect(dx * 32, dy * 32, 32, 32);
            gc.rect(dx * 32, dy * 32, 32, 32);
        }
    }

    // draw the path we've constructed during the loop
    gc.stroke();

    stage.setScene(scene);
    stage.show();
}