画布上的中心文字?

ste*_*wpf 6 text canvas javafx-2

有人可以给我一个关于如何在JavaFX 2 Canvas上居中文本的例子吗?

GraphicsContext有一些像setTextAlign这样的函数,但我不确定如何使用所有这些方法以及我真正需要的方法.我想垂直和水平居中我的文字.

jew*_*sea 19

  1. 将文本对齐设置为居中.
  2. 将文本基线设置为居中.
  3. 在画布的中心绘制文本(通过将其定位在画布宽度和高度的一半).

这是一个示例:

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.VPos;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.layout.StackPane;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class TextCanvas extends Application {
    @Override public void start(Stage primaryStage) {
        Canvas canvas = new Canvas(175, 40);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setTextAlign(TextAlignment.CENTER);
        gc.setTextBaseline(VPos.CENTER);
        gc.fillText(
            "Text centered on your Canvas", 
            Math.round(canvas.getWidth()  / 2), 
            Math.round(canvas.getHeight() / 2)
        );

        StackPane layout = new StackPane();
        layout.getChildren().addAll(canvas);

        primaryStage.setScene(new Scene(layout));
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}
Run Code Online (Sandbox Code Playgroud)

画布上居中的文字