How to draw an 1 pixel line using Javafx Canvas?

Use coordinates in this notation x.5.

Look my example:

    gc.setFill(Color.BLACK);
    gc.setLineWidth(1.0);

    gc.strokeRect(50, 100, 25.0, 25.0);
    gc.strokeRect(100.5, 100.5, 25.0, 25.0);

You will get two squares, the second sharp.

Reference: https://dlsc.com/2014/04/10/javafx-tip-2-sharp-drawing-with-canvas-api/


Imagine each pixel as a (small) rectangle (instead of a point). The integer coordinates are the boundaries between pixels; so a (horizontal or vertical) line with integer coordinates falls "between pixels". This is rendered via antialising, approximating half of the line on one pixel and half on the other. Moving the line 0.5 pixels left or right moves it to the center of the pixel, getting around the issue.

Here's a sample:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SharpCanvasTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Canvas sharpCanvas = createCanvasGrid(600, 300, true);
        Canvas blurryCanvas = createCanvasGrid(600, 300, false);
        VBox root = new VBox(5, sharpCanvas, blurryCanvas);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    
    private Canvas createCanvasGrid(int width, int height, boolean sharp) {
        Canvas canvas = new Canvas(width, height);
        GraphicsContext gc = canvas.getGraphicsContext2D() ;
        gc.setLineWidth(1.0);
        for (double x = sharp ? 0.5 : 0.0; x < width; x+=10) {
            gc.moveTo(x, 0);
            gc.lineTo(x, height);
            gc.stroke();
        }
        
        for (double y = sharp ? 0.5 : 0.0; y < height; y+=10) {
            gc.moveTo(0, y);
            gc.lineTo(width, y);
            gc.stroke();
        }
        return canvas ;
    }

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

And the results:

enter image description here

Tags:

Java

Javafx