[英]How to draw an 1 pixel line using Javafx Canvas?
我一直在谷歌搜索和搜索,發現了一些相關的問題/帖子,但沒有一個解決我的問題。
我使用以下方法直接在畫布(JavaFX)上繪制線條:
gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokeLine(startX, startY, endX, endY);
我想要 1 像素寬度的線。 所以我設置 lineWidth=1。 我明白了:
請注意,線條是模糊的。 它不是 1 像素。 我嘗試將 lineWidth 設置為 0.1 或 0.01 等。它不會改變結果。
順便說一句......我不明白為什么這個參數是雙精度的。 我在某處讀到它與 DPI 有關。 但我不明白單位是什么以及它如何轉換為像素。 Oracle 的文檔沒有幫助。 (或者我沒有找到有幫助的那個)
我想得到這個:
這是在另一個平台上實現的。 請注意,線條很清晰,只有一個 1 像素。
把每個像素想象成一個(小)矩形(而不是一個點)。 整數坐標是像素之間的邊界; 所以具有整數坐標的(水平或垂直)線落在“像素之間”。 這是通過抗鋸齒呈現的,在一個像素上近似一半的線,在另一個像素上近似一半。 將線向左或向右移動 0.5 個像素將其移動到像素的中心,從而解決問題。
這是一個示例:
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);
}
}
結果:
在此符號中使用坐標 x.5。
看我的例子:
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);
你會得到兩個方塊,第二個是銳角。
參考: https : //dlsc.com/2014/04/10/javafx-tip-2-sharp-drawing-with-canvas-api/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.