簡體   English   中英

Javafx Canvas 矩形不畫

[英]Javafx Canvas rect does not draw

我做了一些非常基本的事情,我就是不知道出了什么問題。

我嘗試在 canvas 上繪制網格,這看起來很簡單,但我的矩形輪廓有問題。 他們根本沒有畫!

    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);
        }
    }

結果很有趣,因為它確實繪制了,但不是輪廓......

在此處輸入圖像描述

不可能那么難吧? 我錯過了什么?

您只需將 append 元素添加到路徑中,但您永遠不會對它做任何事情。 您需要使用路徑調用一些方法。 在您的情況下,您需要調用stroke

@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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM