java爱心高级代码
时间: 2024-11-03 09:08:00 浏览: 15
在Java中,创建爱心形状可以使用JavaFX图形API或者Swing库,这里我们提供一个基本的JavaFX方法,它能创建一个彩色的动态爱心动画:
```java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class HeartAnimation extends Application {
private static final int SHAPE_SIZE = 100;
private static final int ROTATION_SPEED = 360 / 10; // 每秒旋转一圈
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Circle circle = new Circle(SHAPE_SIZE / 2);
circle.setFill(Color.RED);
Rectangle rect = new Rectangle(SHAPE_SIZE, SHAPE_SIZE / 4);
rect.setFill(Color.YELLOW);
Polygon polygon = createPolygon(SHAPE_SIZE);
// 添加旋转动画
Rotate rotate = new Rotate();
rotate.setAxis(Rotate.AXIS_Z);
rotate.setAngle(0);
circle.setOnTranslateUpdated(e -> rotate.setAngle(rotate.getAngle() + ROTATION_SPEED));
root.getChildren().addAll(circle, rect, polygon);
Scene scene = new Scene(root, SHAPE_SIZE, SHAPE_SIZE);
primaryStage.setScene(scene);
primaryStage.show();
}
private Polygon createPolygon(int size) {
double[] xPoints = {size, 0, -size, 0};
double[] yPoints = {0, size, 0, -size};
return new Polygon(xPoints, yPoints);
}
public static void main(String[] args) {
launch(args);
}
}
```
这段代码创建了一个包含三个元素(圆形、矩形和三角形)的组合,它们随着时间线一起旋转,形成了动态的爱心效果。你可以根据需要调整颜色、尺寸和动画速度。
阅读全文