可以对边进行FadeTransition吗?

时间:2018-03-22 15:29:58

标签: animation javafx java-2d

我想知道是否有办法从右侧或左侧甚至顶部开始进行FadeTransition,如下例所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

将文本填充设置为线性渐变的样式设置样式,并在时间轴中更改线性渐变的停止点。

这是一个基本示例(点击"淡化标签"查看动画)。类似的方法应该有效淡出。

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TextFade extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Fading label:");
        Label fadingLabel = new Label("text fades in and out");

        DoubleProperty startFade = new SimpleDoubleProperty(0);
        DoubleProperty endFade = new SimpleDoubleProperty(0);
        fadingLabel.styleProperty().bind(Bindings.createStringBinding(() -> String.format(
                "-fx-text-fill: linear-gradient(to right, -fx-text-background-color 0%%, -fx-text-background-color %f%%, transparent %f%%, transparent 100%%);",
                startFade.get()*100, endFade.get()*100
        ), startFade, endFade));


        HBox root = new HBox(2, label, fadingLabel);
        Timeline timeline = new Timeline(
                new KeyFrame(Duration.ZERO, new KeyValue(startFade, 0), new KeyValue(endFade, 0)),
                new KeyFrame(Duration.seconds(1.0/3.0), new KeyValue(startFade, 0)),
                new KeyFrame(Duration.seconds(2.0/3.0), new KeyValue(endFade, 1)),
                new KeyFrame(Duration.seconds(1), new KeyValue(startFade, 1)));

        label.setOnMouseClicked(e -> timeline.play());

        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

enter image description here