java实现爱心飘落
时间: 2023-09-07 14:16:24 浏览: 75
要实现爱心飘落效果,你可以使用 Java 的图形库,比如 AWT 或者 JavaFX。以下是一个使用 JavaFX 实现爱心飘落的示例代码:
```java
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Path;
import javafx.scene.shape.QuadCurveTo;
import javafx.stage.Stage;
import javafx.util.Duration;
public class HeartAnimation extends Application {
private static final double WIDTH = 800;
private static final double HEIGHT = 600;
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT, Color.BLACK);
for (int i = 0; i < 50; i++) {
Circle circle = new Circle(5, Color.RED);
Path path = createHeartPath();
double duration = Math.random() * 5 + 2; // 随机生成动画时长
animateCircleOnPath(circle, path, duration);
root.getChildren().addAll(circle, path);
}
primaryStage.setScene(scene);
primaryStage.show();
}
private Path createHeartPath() {
double centerX = WIDTH / 2;
double centerY = HEIGHT / 2 - 100;
Path path = new Path();
path.setStroke(Color.TRANSPARENT);
path.setFill(Color.TRANSPARENT);
path.getElements().add(new MoveTo(centerX, centerY));
QuadCurveTo curve1 = new QuadCurveTo(0, 0, centerX, centerY + 200);
QuadCurveTo curve2 = new QuadCurveTo(WIDTH, 0, centerX, centerY);
path.getElements().addAll(curve1, curve2);
return path;
}
private void animateCircleOnPath(Circle circle, Path path, double duration) {
Timeline timeline = new Timeline();
timeline.setAutoReverse(true);
KeyValue keyValueX = new KeyValue(circle.centerXProperty(), path.getLayoutBounds().getWidth());
KeyValue keyValueY = new KeyValue(circle.centerYProperty(), path.getLayoutBounds().getHeight());
KeyFrame keyFrame = new KeyFrame(Duration.seconds(duration), keyValueX, keyValueY);
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
public static void main(String[] args) {
launch(args);
}
}
```
以上代码使用 JavaFX 创建了一个窗口,然后在窗口中创建了一组爱心形状的圆,并使用动画让这些圆沿着一个心形路径飘落。你可以运行这段代码来查看效果。请注意,你可能需要在项目中添加 JavaFX 的相关依赖。
希望对你有帮助!如果你有任何问题,请随时问我。
阅读全文