JavaFX:通过绘制来擦除线条

5

我刚接触JavaFX,现在正在尝试在画布上绘制一些东西。

首先,我将线条颜色设置为黑色并绘制了一条线。

canvas.getGraphicsContext2D().setStroke(Color.BLACK);
canvas.getGraphicsContext2D().strokeLine(20,20,100,100);

接下来我尝试通过绘制一条白线来擦除这条线:

canvas.getGraphicsContext2D().setStroke(Color.WHITE);  
canvas.getGraphicsContext2D().strokeLine(20,20,100,100);

画布上可能会有一些灰色像素。这是什么原因,如何防止出现这种情况?

下面是我创建场景的方式:

Pane root = new Pane();
canvas = new Canvas(200, 200);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.strokeLine(20,20,100,100);
scene = new Scene(root, 200, 200);
this.setColor(Color.WHITE);
root.getChildren().add(canvas);

感谢,Martin。

Canvas 的背景颜色是否设置为白色? - SedJ601
是的,我尝试过 canvas.setStyle("-fx-background-color: white;");((Pane)scene.getRoot()).setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); - Ma Sch
1
我发现了一些奇怪的事情,它过一会儿就变白了。尝试循环13次。 - Kiraged
@Emrage的评论让我怀疑存在别名伪像;请[编辑]您的问题,包括一个[mcve]以展示您所描述的问题。 - trashgod
请看我上面的编辑。有没有办法禁用抗锯齿? - Ma Sch
1个回答

0

这个问题与抗锯齿相关。如果某个点具有非整数坐标,则其绘制将被分成几个部分填充的像素。就像这样(在缩放时):enter image description here 因此,如果你想绘制与水平或垂直线不同的图形,你会得到这种效果。如果您想避免这种效果,请使用逐像素绘制:

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {
        Canvas canvas = new Canvas();
        canvas.setWidth(200);
        canvas.setHeight(200);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        gc.setLineWidth(4);
        gc.setStroke(Color.BLACK);
        drawLine(gc, 20, 20, 180, 180);
        gc.setStroke(Color.WHITE);
        drawLine(gc, 20, 20, 180, 180);

        Pane pane = new Pane(canvas);
        primaryStage.setScene(new Scene(pane));
        primaryStage.show();
    }

    private void drawLine(GraphicsContext gc, double x1, double y1, double x2, double y2) {
        double lineWidth = gc.getLineWidth();
        Color color = (Color) gc.getStroke();
        PixelWriter pw = gc.getPixelWriter();

        double k = (y2 - y1) / (x2 - x1);
        double b = (x1 * y2 - x2 * y1) / (x1 - x2);

        int val;
        for (int x = (int) x1; x <= (int) x2; x++) {
            val = (int) (k * x + b);
            for (int y = (int) (val - (lineWidth-1) / 2); y < val + lineWidth / 2; y++) {
                pw.setColor(x, y, color);
            }
        }

    }


    public static void main(String[] args) {
        launch(args);
    }
}

它能工作,但是过于复杂了。你需要为不同的形状创建很多方法。最好的解决方案是清理并重新绘制需要改变的部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接