Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text on Canvas?

Can someone please give me an example on how to center text on a JavaFX 2 Canvas?

GraphicsContext has some functions like setTextAlign, but I am not sure on how to use all those methods and which of them I really need. I want to center my text vertically and horizontally.

like image 264
stefan.at.wpf Avatar asked Feb 14 '13 19:02

stefan.at.wpf


People also ask

How do I center text in canvas?

To align HTML5 Canvas text, we can use the textAlign property of the canvas context, which can be set to start, end, left, center, or right. The alignment is relative to an imaginary vertical line at the x position of the text defind by fillText() or strokeText().

How do you center something on canvas?

If you are selecting more than one item, check the “Align to Canvas” box in the design tab of the inspector panel. Choose the align left, center, or right, or the top, middle, or bottom icons to align objects respectively to the canvas.

How do I align text to the center?

Center the text vertically between the top and bottom margins. Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.

How do I vertically align text in canvas?

How do I vertically align text in canvas? To vertically align text with HTML5 Canvas, we can use the textBaseline property of the canvas context. textBaseline can be set with one of the following values: top, hanging, middle, alphabetic, ideographic, and bottom.


1 Answers

  1. Set the text align to center.
  2. Set the text baseline to center.
  3. Draw the text in the center of your canvas (by positioning it at half the canvas width and height).

Here is a sample:

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); }
}

centered text on canvas

like image 132
jewelsea Avatar answered Sep 20 '22 21:09

jewelsea