如何沿着贝塞尔曲线书写文本?

18

我希望在JavaFX 2.2或者至少是JavaFX 8中做类似于这样的效果。我查阅了Text javadoccss reference,但没有找到结果。

在此输入图片描述

通过在WebView中显示svg来实现这种效果是可行的。但我的应用程序需要显示很多带有这种效果的文本。WebView是一个太重的组件,无法绘制这种效果的文本。

我在Oracle Technology Network上问过同样的问题。


我不知道这对你是否有帮助。我必须在Unity3D中沿着贝塞尔曲线移动图形,我们使用了SVG跟踪路径(因为我们有起始的SVG)。这是我们用来构建库的内容;http://www.w3.org/TR/SVG/paths.html - MichelleJS
@MichelleJS 谢谢,但是SVG在JavaFX中并不被完全支持。 - gontard
也许这个链接可以帮到你:https://forums.oracle.com/thread/1712335 - zhujik
@Sebastian 我看到了这个讨论。但是答案很深奥。 - gontard
2个回答

28

这是对PathTransition的滥用,以便在Bézier Curve上绘制文本。

该程序允许您拖动控制点来定义曲线,然后沿着该曲线绘制文本。文本中的字符间距相等,因此最好使曲线的总长度与"正常"间距的文本宽度相匹配,并且不进行像字距调整之类的调整。

下面的示例显示:

  1. 带有glow效果的曲线文本。
  2. 一些没有应用效果的曲线文本。
  3. 用于定义曲线路径的控制操作点,以及沿着该路径绘制无效果文本的方式。

Curved Text With Glow Curved Text Curve Manipulator

这个解决方案是基于StackOverflow问题的答案进行的快速hack: CubicCurve JavaFX。我相信如果花费更多的精力、时间和技能,一定可以找到更好的解决方案。

由于程序是基于转换的,很容易将其调整为使文本动画跟随曲线,当溢出时从右侧包装回左侧(就像你可能在marquee text或股票滚动条中看到的那样)。

任何标准的JavaFX效果,如发光、阴影等以及字体变化都可以应用于获得类似于你问题中PaintShop Pro文本的阴影效果。在这里应用一个发光效果是一个不错的选择��因为它会轻微地软化旋转字符周围的锯齿状边缘。

此外,此解决方案基于的PathTransition可以接受任意形状作为路径输入,因此文本可以遵循其他类型的路径,而不仅仅是立方曲线。

import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.collections.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.effect.Glow;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * Example of drawing text along a cubic curve.
 * Drag the anchors around to change the curve.
 */
public class BezierTextPlotter extends Application {
    private static final String CURVED_TEXT = "Bézier Curve";

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

    @Override
    public void start(final Stage stage) throws Exception {
        final CubicCurve curve = createStartingCurve();

        Line controlLine1 = new BoundLine(curve.controlX1Property(), curve.controlY1Property(), curve.startXProperty(), curve.startYProperty());
        Line controlLine2 = new BoundLine(curve.controlX2Property(), curve.controlY2Property(), curve.endXProperty(), curve.endYProperty());

        Anchor start = new Anchor(Color.PALEGREEN, curve.startXProperty(), curve.startYProperty());
        Anchor control1 = new Anchor(Color.GOLD, curve.controlX1Property(), curve.controlY1Property());
        Anchor control2 = new Anchor(Color.GOLDENROD, curve.controlX2Property(), curve.controlY2Property());
        Anchor end = new Anchor(Color.TOMATO, curve.endXProperty(), curve.endYProperty());

        final Text text = new Text(CURVED_TEXT);
        text.setStyle("-fx-font-size: 40px");
        text.setEffect(new Glow());
        final ObservableList<Text> parts = FXCollections.observableArrayList();
        final ObservableList<PathTransition> transitions = FXCollections.observableArrayList();
        for (char character : text.textProperty().get().toCharArray()) {
            Text part = new Text(character + "");
            part.setEffect(text.getEffect());
            part.setStyle(text.getStyle());
            parts.add(part);
            part.setVisible(false);

            transitions.add(createPathTransition(curve, part));
        }

        final ObservableList<Node> controls = FXCollections.observableArrayList();
        controls.setAll(controlLine1, controlLine2, curve, start, control1, control2, end);

        final ToggleButton plot = new ToggleButton("Plot Text");
        plot.setOnAction(new PlotHandler(plot, parts, transitions, controls));

        Group content = new Group(controlLine1, controlLine2, curve, start, control1, control2, end, plot);
        content.getChildren().addAll(parts);

        stage.setTitle("Cubic Curve Manipulation Sample");
        stage.setScene(new Scene(content, 400, 400, Color.ALICEBLUE));
        stage.show();
    }

    private PathTransition createPathTransition(CubicCurve curve, Text text) {
        final PathTransition transition = new PathTransition(Duration.seconds(10), curve, text);

        transition.setAutoReverse(false);
        transition.setCycleCount(PathTransition.INDEFINITE);
        transition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
        transition.setInterpolator(Interpolator.LINEAR);

        return transition;
    }

    private CubicCurve createStartingCurve() {
        CubicCurve curve = new CubicCurve();
        curve.setStartX(50);
        curve.setStartY(200);
        curve.setControlX1(150);
        curve.setControlY1(300);
        curve.setControlX2(250);
        curve.setControlY2(50);
        curve.setEndX(350);
        curve.setEndY(150);
        curve.setStroke(Color.FORESTGREEN);
        curve.setStrokeWidth(4);
        curve.setStrokeLineCap(StrokeLineCap.ROUND);
        curve.setFill(Color.CORNSILK.deriveColor(0, 1.2, 1, 0.6));
        return curve;
    }

    class BoundLine extends Line {
        BoundLine(DoubleProperty startX, DoubleProperty startY, DoubleProperty endX, DoubleProperty endY) {
            startXProperty().bind(startX);
            startYProperty().bind(startY);
            endXProperty().bind(endX);
            endYProperty().bind(endY);
            setStrokeWidth(2);
            setStroke(Color.GRAY.deriveColor(0, 1, 1, 0.5));
            setStrokeLineCap(StrokeLineCap.BUTT);
            getStrokeDashArray().setAll(10.0, 5.0);
        }
    }

    // a draggable anchor displayed around a point.
    class Anchor extends Circle {
        Anchor(Color color, DoubleProperty x, DoubleProperty y) {
            super(x.get(), y.get(), 10);
            setFill(color.deriveColor(1, 1, 1, 0.5));
            setStroke(color);
            setStrokeWidth(2);
            setStrokeType(StrokeType.OUTSIDE);

            x.bind(centerXProperty());
            y.bind(centerYProperty());
            enableDrag();
        }

        // make a node movable by dragging it around with the mouse.
        private void enableDrag() {
            final Delta dragDelta = new Delta();
            setOnMousePressed(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    // record a delta distance for the drag and drop operation.
                    dragDelta.x = getCenterX() - mouseEvent.getX();
                    dragDelta.y = getCenterY() - mouseEvent.getY();
                    getScene().setCursor(Cursor.MOVE);
                }
            });
            setOnMouseReleased(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    getScene().setCursor(Cursor.HAND);
                }
            });
            setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    double newX = mouseEvent.getX() + dragDelta.x;
                    if (newX > 0 && newX < getScene().getWidth()) {
                        setCenterX(newX);
                    }
                    double newY = mouseEvent.getY() + dragDelta.y;
                    if (newY > 0 && newY < getScene().getHeight()) {
                        setCenterY(newY);
                    }
                }
            });
            setOnMouseEntered(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    if (!mouseEvent.isPrimaryButtonDown()) {
                        getScene().setCursor(Cursor.HAND);
                    }
                }
            });
            setOnMouseExited(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    if (!mouseEvent.isPrimaryButtonDown()) {
                        getScene().setCursor(Cursor.DEFAULT);
                    }
                }
            });
        }

        // records relative x and y co-ordinates.
        private class Delta {
            double x, y;
        }
    }

    // plots text along a path defined by provided bezier control points.
    private static class PlotHandler implements EventHandler<ActionEvent> {
        private final ToggleButton plot;
        private final ObservableList<Text> parts;
        private final ObservableList<PathTransition> transitions;
        private final ObservableList<Node> controls;

        public PlotHandler(ToggleButton plot, ObservableList<Text> parts, ObservableList<PathTransition> transitions, ObservableList<Node> controls) {
            this.plot = plot;
            this.parts = parts;
            this.transitions = transitions;
            this.controls = controls;
        }

        @Override
        public void handle(ActionEvent actionEvent) {
            if (plot.isSelected()) {
                for (int i = 0; i < parts.size(); i++) {
                    parts.get(i).setVisible(true);
                    final Transition transition = transitions.get(i);
                    transition.stop();
                    transition.jumpTo(Duration.seconds(10).multiply((i + 0.5) * 1.0 / parts.size()));
                    // just play a single animation frame to display the curved text, then stop
                    AnimationTimer timer = new AnimationTimer() {
                        int frameCounter = 0;

                        @Override
                        public void handle(long l) {
                            frameCounter++;
                            if (frameCounter == 1) {
                                transition.stop();
                                stop();
                            }
                        }
                    };
                    timer.start();
                    transition.play();
                }
                plot.setText("Show Controls");
            } else {
                plot.setText("Plot Text");
            }

            for (Node control : controls) {
                control.setVisible(!plot.isSelected());
            }

            for (Node part : parts) {
                part.setVisible(plot.isSelected());
            }
        }
    }
}

另一个可能的解决方案是测量每个文本字符并进行数学插值以在不使用PathTransition的情况下插入文本位置和旋转。但是,PathTransition已经存在并且对我来说运行良好(也许文本进度的曲线距离测量仍然会使我感到挑战)。
附加问题的答案
您认为通过调整您的代码可以实现javafx.scene.effect.Effect吗?
不行。实现效果需要执行用于沿着贝塞尔曲线显示文本的数学计算,而我的答案不提供此功能(它仅采用现有的PathTransition完成此操作)。
此外,JavaFX 2.2中没有公共API可用于实现自定义效果。
存在DisplacementMap效果,可能可用于获得类似的效果。但是,我认为使用DisplacementMap效果(以及可能调整文本布局的任何效果)可能会扭曲文本。

在我看来,沿着贝塞尔曲线编写文本更多的是与布局相关而不是特效相关——最好调整字符的布局和旋转,而不是使用特效来移动它们。

或者也许有更好的方法将其正确地集成到JFX框架中?

您可以子类化Pane并创建一个自定义的PathLayout,类似于FlowPane,但是沿路径而不是直线布置节点。要布置的节点由每个字符的Text节点组成,类似于我在答案中所做的。但即便如此,您仍然不能真正准确地呈现文本,因为您需要考虑诸如等宽字母、kerning等问题。因此,要实现完全的保真度和准确性,您需要实现自己的低级文本布局算法。如果是我的话,只有在使用PathTransitions提供的“足够好”的解决方案对您来说不够高质量时,才会去做这项工作。


好的回答,谢谢!您认为通过调整您的代码可以实现javafx.scene.effect.Effect吗?或者也许有更好的方法将其正确地集成到JFX框架中? - gontard
@gontard 我编辑了我的答案以回答你的额外问题。 - jewelsea
感谢您提供这些详细信息和完整的答案。我想我会创建一个自定义面板,基于AnimationPathHelper或PathIterator。再次感谢您花费时间。 - gontard
@jewelsea 最近在JavaFx 8方面有没有相关的新进展?我真的很想在Bezier曲线上拥有比例间距的字形...我想知道像这样“黑客”一些东西有多难。首先,我该如何在JavaFx中找出字形宽度和字距信息呢? - user2499946
尝试向openjfx-dev邮件列表询问有关JavaFX中字形测量的问题。 - jewelsea

8
你可以使用WebView和一些html来显示svg。以下是一个示例:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class CurvedText extends Application {

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

  @Override
  public void start(Stage primaryStage) throws Exception {
    StackPane root = new StackPane();
    WebView view = new WebView();
    view.getEngine().loadContent("<!DOCTYPE html>\n" +
            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
            "  <body>\n" +
            "<embed width=\"100\" height=\"100\" type=\"image/svg+xml\" src=\"path.svg\">\n" +
            "  <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" +
            "<defs>\n" +
            "  <path id=\"textPath\" d=\"M10 50 C10 0 90 0 90 50\"/>\n" +
            "</defs>\n"+
            "<text fill=\"red\">\n" +
            "  <textPath xlink:href=\"#textPath\">Text on a Path</textPath>\n" +
            "</text>" +
            "</svg>\n" +
            "</embed>" +
            "  </body>\n" +
            "</html>");
    root.getChildren().add(view);
    Scene scene = new Scene(root, 500, 500);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

结果:

enter image description here

根据我的经验,这并不是最佳解决方案,因为JavaFX WebView在应该像标签一样的情况下行为有些棘手,但它可以作为一个开始。

编辑

如果你不想直接使用WebView,则可以使用单个实例的WebView来呈现带有HTML的场景,然后对其进行快照以生成ImageView。请参考此示例:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class CurvedText extends Application {

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

  @Override
  public void start(Stage primaryStage) throws Exception {
    final HBox root = new HBox();
    final WebView view = new WebView();
    view.getEngine().loadContent("<!DOCTYPE html>\n" +
            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
            "  <body>\n" +
            "<embed width=\"100\" height=\"100\" type=\"image/svg+xml\" src=\"path.svg\">\n" +
            "  <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" +
            "<defs>\n" +
            "  <path id=\"textPath\" d=\"M10 50 C10 0 90 0 90 50\"/>\n" +
            "</defs>\n"+
            "<text fill=\"red\">\n" +
            "  <textPath xlink:href=\"#textPath\">Text on a Path</textPath>\n" +
            "</text>" +
            "</svg>\n" +
            "</embed>" +
            "  </body>\n" +
            "</html>");
    root.getChildren().add(view);
    view.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
      @Override
      public void changed(ObservableValue<? extends Worker.State> arg0, Worker.State oldState, Worker.State newState) {
        if (newState == Worker.State.SUCCEEDED) {
          // workaround for https://javafx-jira.kenai.com/browse/RT-23265
          AnimationTimer waitForViewToBeRendered = new AnimationTimer(){
            private int frames = 0;
            @Override
            public void handle(long now) {
              if (frames++ > 3){
                WritableImage snapshot = view.snapshot(null, null);
                ImageView imageView = new ImageView(snapshot);
                root.getChildren().add(imageView);
                this.stop();
              }
            }
          };
          waitForViewToBeRendered.start();
        }
      }
    });
    Scene scene = new Scene(root, 500, 500);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

感谢您的贡献。我应该提到使用 WebView 不可接受,因为我的应用程序将需要显示大量具有此效果的文本。WebView 是一个太重的组件,无法绘制具有此效果的文本。 - gontard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接