SomethingSomething SomethingSomething - 1 month ago 6
Java Question

Java: apply geometrically-transformed text on an image

I know it is possible to apply standard text on image using

BufferedImage
's
getGraphics
:

Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
g.drawString("Hello World!", 100, 100);
g.dispose()


I am trying to create an application, in which I'll be able to apply text with geometrical transformations (e.g. rotation, shearing, projection), such that I can finally get images which look like:

ImageSample

Is there is a general way to apply text with geometric transformations, like in the above image?

Answer

JavaFX is "considered standard" since Java 8 and has this built in easy to use. You can apply any transformation to a Text object and use a StackPane to put it on top of the image.

public class MyApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {

        ImageView lena = new ImageView(new Image("main/Lenna.png")); //URL to image

        Text text1 = new Text("Hello World!");
        text1.setRotate(30);
        text1.setTranslateX(100);
        text1.setTranslateY(-100);
        text1.setFont(Font.font("Veranda", FontWeight.BOLD, 36));
        text1.setFill(Color.BLUE);

        Text text2 = new Text("Hello Lenna!");
        PerspectiveTransform perspectiveTrasform = new PerspectiveTransform();
        perspectiveTrasform.setUlx(10);
        perspectiveTrasform.setUly(10);
        perspectiveTrasform.setUrx(300);
        perspectiveTrasform.setUry(40);
        perspectiveTrasform.setLrx(300);
        perspectiveTrasform.setLry(60);
        perspectiveTrasform.setLlx(10);
        perspectiveTrasform.setLly(90);
        text2.setEffect(perspectiveTrasform);
        text2.setFont(Font.font("Veranda", FontWeight.BOLD, 36));

        StackPane pane = new StackPane(lena, text1, text2);
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) throws Exception {

        launch(args);
    }
}

enter image description here

See also Applying Effects to Text for more info.