Center text on canvas?
•
Java
Can anyone give an example of how to centralize text on JavaFX 2 canvas?
Graphicscontext has some functions like settextalign, but I'm not sure how to use all these methods and what I really need I want to center my text vertically and horizontally
Solution
>Set text alignment to center
Here is an example:
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); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码