如何动画虚线Javafx

时间:2016-04-19 19:32:31

标签: java animation line javafx-8

我想在这一行中移动(动画)破折号:

  Line l=new Line();
  l.getStrokeDashArray().addAll(25d, 20d, 5d, 20d);

1 个答案:

答案 0 :(得分:3)

将线条的stokeDashOffsetProperty从值0设置为动画线迹数组中项目的总长度。如果你想以相反的方向制作动画,只需反向运行timeline

offset1 offset2

import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;

public class LineStrokeAnimator extends Application {
    @Override public void start(Stage stage) {
        Line line = new Line(20, 100, 80, 20);
        line.getStrokeDashArray().setAll(25d, 20d, 5d, 20d);
        line.setStrokeWidth(2);

        final double maxOffset = 
                line.getStrokeDashArray().stream()
                        .reduce(
                                0d, 
                                (a, b) -> a + b
                        );

        Timeline timeline = new Timeline(
                new KeyFrame(
                        Duration.ZERO, 
                        new KeyValue(
                                line.strokeDashOffsetProperty(), 
                                0, 
                                Interpolator.LINEAR
                        )
                ),
                new KeyFrame(
                        Duration.seconds(2), 
                        new KeyValue(
                                line.strokeDashOffsetProperty(), 
                                maxOffset, 
                                Interpolator.LINEAR
                        )
                )
        );
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();

        stage.setScene(new Scene(new Group(line), 100, 120));
        stage.show();
    }

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