JavaFx画布填充文本呈现质量

时间:2018-11-18 19:06:21

标签: java canvas javafx paint graphicscontext

我正在使用画布来表示图的JavaFx应用程序。画布正在使用graphicsContext.fillText()绘制文本。在下面的图像中,画布在右侧,左侧是使用相同字体的Label。我的问题是,应该使用哪个调整参数使右边的文本与左边的文本相同?

Label vs Canvas using Monospaced font

public class SampleRenderingIssue extends Application {
    private final StackPane root = new StackPane();
    private final Scene scene = new Scene(root, 300, 250);
    private final BorderPane pane = new BorderPane();
    private final Canvas canvas = new Canvas();


    @Override
    public void start(Stage stage) {
        stage.setTitle("Sample Canvas");

        VBox vbox = new VBox();
        VBox.setVgrow(pane, Priority.ALWAYS);
        vbox.getChildren().addAll( pane );

        pane.getChildren().add(canvas);
        root.getChildren().add(vbox);
        stage.setScene(scene);
        stage.sizeToScene();
        setupCanvasPane();
        stage.show();
        Platform.runLater(()-> paint());
    }
    private void setupCanvasPane(){
        canvas.widthProperty().bind(pane.widthProperty());
        canvas.heightProperty().bind(pane.heightProperty());
        pane.widthProperty().addListener((o,p,c)-> paint());
        paint();
    }

    public void paint(){
        GraphicsContext gr = canvas.getGraphicsContext2D();
        gr.clearRect( 0,0, canvas.getWidth(), canvas.getHeight() );
        gr.setFill( Color.web("#222222") );
        gr.fillRect( 0,0,canvas.getWidth(), canvas.getHeight());
        gr.setStroke( Color.WHITE );
        gr.setFill( Color.WHITE );
        gr.setLineWidth( 1d );
        gr.strokeLine( 0,0, canvas.getWidth(), canvas.getHeight() );
        gr.setFont( Font.font( "Candara"));
        gr.fillText("This is a text", 100, 100 );
        gr.setFont( Font.font( "Monospaced"));
        gr.fillText("This is a text", 100, 120 );
    }

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

}

此问题在FullHd显示屏上重现,其中“控制面板”中的Windows比例设置为125%(笔记本电脑的默认值)。

enter image description here

1 个答案:

答案 0 :(得分:1)

我在Canvas中的文本呈现质量也很差。我以较小的字体显示密集的文本,以前看起来很难看。

这可能与您遇到的问题完全相同,因为我的Windows缩放比例为100%,但是我发现它是由Canvas使用相同与其他UI小部件一样执行ClearType实现。它似乎设置为GREY模式,而不是LCD。这是一个简单的单行修复程序:

        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFontSmoothingType(FontSmoothingType.LCD);
        gc.setFont(Font.font("Consolas", 10));
        gc.fillText("Example ABC 123", 10, 10);

这是结果,在每种情况下,顶行都是渲染的版本,而底行是场景中的Label。我提供了一个放大版本,您可以清楚地看到Canvas没有正确执行LCD亚像素渲染

enter image description here

在右手柄示例中,它们看起来是相同的,并且恢复了我的视觉质量。