当我最初开始使用Canvas API时,我注意到渲染代码的结果有些模糊,甚至更糟,不一致。 有些线条模糊,有些线条清晰。 来自Swing,我花了一些时间才意识到这是由JavaFX的坐标系引起的,该坐标系允许双精度渲染。
为了解决这个问题,所需要的只是在“中间”使用坐标。 因此,在我的代码中,您现在可以找到很多称为snapXZY()的方法(可以在JavaFX代码本身中找到类似的方法),该方法首先将给定的坐标转换为整数,然后将其添加.5。 以下屏幕截图显示了使用这种方法的区别。 下面的代码用于此示例:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* Tip 2: How to render sharp lines in a canvas.
*/
public class Tip2DrawingSharpLinesInCanvas extends
Application {
class MyCanvas extends Canvas {
public MyCanvas(boolean drawSharpLines) {
setWidth(150);
setHeight(150);
double w = getWidth();
double h = getHeight();
GraphicsContext gc = getGraphicsContext2D();
gc.clearRect(0, 0, w, h);
gc.setStroke(Color.GRAY);
gc.strokeRect(0, 0, w, h);
for (double y = 20; y <= h - 20; y += 10) {
if (drawSharpLines) {
// Snap the y coordinate
gc.strokeLine(10,
snap(y),
w - 10,
snap(y));
} else {
gc.strokeLine(10, y, w - 10, y);
}
}
}
private double snap(double y) {
return ((int) y) + .5;
}
}
@Override
public void start(Stage stage) throws Exception {
MyCanvas canvasBlurry = new MyCanvas(false);
MyCanvas canvasSharp = new MyCanvas(true);
Label labelBlurry = new Label("Blurry");
Label labelSharp = new Label("Sharp");
VBox.setMargin(canvasBlurry, new Insets(10));
VBox.setMargin(canvasSharp, new Insets(10));
VBox.setMargin(labelBlurry,
new Insets(10, 10, 0, 10));
VBox.setMargin(labelSharp,
new Insets(10, 10, 0, 10));
VBox box = new VBox();
box.getChildren().add(labelBlurry);
box.getChildren().add(canvasBlurry);
box.getChildren().add(labelSharp);
box.getChildren().add(canvasSharp);
stage.setScene(new Scene(box));
stage.setTitle("Tip 2: Sharp Lines in Canvas");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
翻译自: https://www.javacodegeeks.com/2014/04/javafx-tip-2-sharp-drawing-with-canvas-api.html