如何绘制与文本节点相交的线而不查看节点内的线

时间:2017-09-12 19:48:22

标签: css javafx drawing intersection

我想绘制一条垂直线,该垂直线可能与文本对象相交。当我这样做而没有任何修改时,该行直接通过该单词,使该单词难以阅读。我想这样做,以便线到达文本时消失,并在文本节点后立即继续。我已经尝试使用带有css背景的toBack()来为文本创建一个正方形,但看起来文本节点具有透明背景,因此该行仍然可以在字母后面看到。是否有另一种方法可以使文本不与线相交?请注意,文本可能一直存在,也可能不存在,并且由于程序的性质,它可以处于任何坐标,所以我不能只绘制两行(一行在文本之前,一行在之后)。

1 个答案:

答案 0 :(得分:1)

使用Label代替Text会让事情变得更轻松。 Label(最终)是Region的子类,因此它具有可以设置样式的背景颜色等属性,允许它具有不透明的背景。使用CSS规则

-fx-background-color: -fx-background ;
标签上的

将为其指定默认背景颜色。相比之下,TextShape的子类,只有fillstroke等属性,它们对构成文本的字形的内部和外部进行着色,分别

所以你可以做到

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class TextVsLabel extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane labelPane = new StackPane();
        labelPane.setMinSize(250, 250);

        Label label = new Label("A Label");
        label.setStyle("-fx-background-color: -fx-background;");

        labelPane.getChildren().add(label);
        addLineToPane(labelPane);

        StackPane textPane = new StackPane();
        textPane.setMinSize(250, 250);
        textPane.getChildren().add(new Text("A Text"));
        addLineToPane(textPane);

        HBox root = new HBox(5, labelPane, textPane);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void addLineToPane(Pane pane) {
        Line line = new Line();
        line.startXProperty().bind(pane.widthProperty().divide(2));
        line.endXProperty().bind(line.startXProperty());
        line.setStartY(0);
        line.endYProperty().bind(pane.heightProperty());

        // add line to beginning of pane's parent list, so it appears
        // behind everything else
        pane.getChildren().add(0, line);
    }

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

导致

enter image description here

请注意,如果标签中的文本周围需要更多空间,则可以在标签上添加填充:-fx-padding: 1em;等。

相关问题