Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw an 1 pixel line using Javafx Canvas?

Tags:

java

javafx

I've been googling and searching, found some some related questions/posts but none of the address my problem.

I am drawing lines directly on canvas (JavaFX) using:

gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokeLine(startX, startY, endX, endY);

I want 1 pixel width lines. So I set lineWidth=1. I get this: enter image description here

Note that the lines are blurred. It is not 1 pixel. I've tried to set lineWidth to 0.1 or 0.01, etc. It does not change the result.

By the way... I do not understand why this parameter is a double. I read somewhere that it has to do with DPI. But I do not understand what is the unit and how it is converted to pixels. Oracle's documentation does not help. (or I did not find the one that helps)

I'd like to get this instead:

enter image description here

This was implemented in another platform. Note that lines are sharp and have just one 1 pixel.

like image 829
Chocksmith Avatar asked Jan 08 '15 18:01

Chocksmith


People also ask

What is JavaFX scene canvas?

JavaFX Canvas. last modified January 6, 2022. Canvas is an image that can be drawn on using a set of graphics commands provided by a GraphicsContext . It is a high-level tool for doing painting. GraphicsContext is used to issue draw calls to a Canvas using a buffer.

What is GraphicsContext?

This class is used to issue draw calls to a Canvas using a buffer. Each call pushes the necessary parameters onto the buffer where they will be later rendered onto the image of the Canvas node by the rendering thread at the end of a pulse.


1 Answers

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/

like image 61
Fausto Odilon Avatar answered Oct 07 '22 06:10

Fausto Odilon