Измените круг на квадрат, чтобы заполнить квадрат в JavaFX - PullRequest
0 голосов
/ 30 марта 2020

Я обнаружил удивительную анимацию, в которой происходит переход от круга / эллипса к квадрату, и незадолго до окончания анимации квадрат немного выступает, а затем снова подгоняет его к нужному размеру.

Источник: https://clementmihailescu.github.io/Pathfinding-Visualizer/#

Я пытался воссоздать его, но не смог получить эффект перехода от капли чернил к квадрату.

package sample;

import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.Lighting;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.util.Duration;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    Pane root = new Pane();
    Rectangle originalRectangle = new Rectangle(100,100);
    originalRectangle.setFill(Color.WHITE);
    originalRectangle.setStroke(Color.BLUE);
    Rectangle substituteRectangle = new Rectangle(25,25,50,50);
    substituteRectangle.setOpacity(0.0);
    substituteRectangle.setFill(Color.TURQUOISE);
    substituteRectangle.setStroke(Color.TURQUOISE);
    Rectangle yellowRectangle = new Rectangle(100,100);
    yellowRectangle.setFill(Color.YELLOW);
    root.getChildren().addAll(originalRectangle,substituteRectangle,yellowRectangle);


    FadeTransition fadeOutTransition = new FadeTransition(Duration.millis(3000),yellowRectangle);    //Make the duration as 1ms to get the instant 
    fadeOutTransition.setFromValue(1.0);
    fadeOutTransition.setToValue(0.0);

    FadeTransition fadeInTransition = new FadeTransition(Duration.millis(1),substituteRectangle);
    fadeInTransition.setFromValue(0.0);
    fadeInTransition.setToValue(0.8);

//To make the square protrute out a bit
    ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(4),substituteRectangle);
    scaleTransition.setToX(2.1);
    scaleTransition.setToY(2.1);

    ParallelTransition parallelTransition = new ParallelTransition(scaleTransition,fadeInTransition);

    fadeOutTransition.play();
    fadeOutTransition.setOnFinished(e -> {
        parallelTransition.setOnFinished(event -> {
            root.getChildren().removeAll(substituteRectangle,yellowRectangle);
            originalRectangle.setOpacity(1.0);
            originalRectangle.setFill(Color.RED);
        });
        parallelTransition.play();
    });
    Scene scene = new Scene(root,800,600);
    primaryStage.setScene(scene);
    primaryStage.show();
}

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

1 Ответ

2 голосов
/ 30 марта 2020

Вероятно, самый простой способ достижения такой анимации - просто анимировать радиус круга и ограничить его размер, используя Rectangle в качестве клипа. Также часто Timeline предоставляет анимацию, которая хорошо подходит для замены нескольких переходов. В этом случае тот факт, что он допускает анимацию между цветами, а также анимацию для DoubleProperty, делает этот выбор хорошим для упрощения анимации:

@Override
public void start(Stage primaryStage) throws Exception {
    Pane root = new Pane();
    Rectangle bounds = new Rectangle(50, 50, 100, 100);
    Circle circle = new Circle(bounds.getX() + 0.5 * bounds.getWidth(), bounds.getY() + 0.5 * bounds.getHeight(),
            0);
    circle.setClip(bounds);
    root.getChildren().add(circle);

    Timeline animation = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(circle.fillProperty(), Color.BLUE),
                    new KeyValue(circle.radiusProperty(), 0d)),
            new KeyFrame(Duration.seconds(5), new KeyValue(circle.fillProperty(), Color.RED), new KeyValue(
                    circle.radiusProperty(), 0.5 * Math.hypot(bounds.getWidth(), bounds.getHeight())))); // at the end of the animation the circle should reach the corners -> diameter = diagonale of rect

    root.setOnMouseClicked(evt -> animation.playFromStart());

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