用Javafx实现汽车上雨刷器摆动的动画(雨刷器用画线描绘)
时间: 2023-12-06 22:39:39 浏览: 139
以下是一个简单的实现汽车上雨刷器摆动的动画的 Javafx 代码示例,其中雨刷器用画线描绘:
```java
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CarWindShieldWiper extends Application {
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
private static final int CANVAS_WIDTH = 600;
private static final int CANVAS_HEIGHT = 400;
private static final int WIPER_LENGTH = 60;
private static final int WIPER_WIDTH = 5;
private static final int WIPER_SPEED = 5;
private int angle = 0;
private boolean reverse = false;
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
Group root = new Group(canvas);
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
animateWiper(gc);
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
Scene scene = new Scene(root, WINDOW_WIDTH, WINDOW_HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
}
private void animateWiper(GraphicsContext gc) {
gc.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
gc.setStroke(Color.BLACK);
gc.setLineWidth(2);
// 绘制雨刷器底部
gc.strokeLine(CANVAS_WIDTH / 2 - WIPER_LENGTH / 2, CANVAS_HEIGHT - WIPER_WIDTH, CANVAS_WIDTH / 2 + WIPER_LENGTH / 2, CANVAS_HEIGHT - WIPER_WIDTH);
gc.setFill(Color.GRAY);
gc.fillRect(CANVAS_WIDTH / 2 - WIPER_LENGTH / 2, CANVAS_HEIGHT - WIPER_WIDTH, WIPER_LENGTH, WIPER_WIDTH);
// 绘制雨刷器
gc.setStroke(Color.BLACK);
gc.setLineWidth(3);
int x1 = CANVAS_WIDTH / 2;
int y1 = CANVAS_HEIGHT - WIPER_WIDTH;
int x2 = (int) (x1 + WIPER_LENGTH * Math.cos(Math.toRadians(angle)));
int y2 = (int) (y1 - WIPER_LENGTH * Math.sin(Math.toRadians(angle)));
gc.strokeLine(x1, y1, x2, y2);
// 更新角度
if (reverse) {
angle -= WIPER_SPEED;
if (angle < -45) {
reverse = false;
}
} else {
angle += WIPER_SPEED;
if (angle > 45) {
reverse = true;
}
}
}
public static void main(String[] args) {
launch(args);
}
}
```
在这个示例中,我们使用 `Canvas` 类创建了一个画布,并在画布上绘制了雨刷器。`Timeline` 类用于控制动画的运行,我们在每个时间步长上更新雨刷器的位置和旋转角度。通过改变旋转角度,我们可以实现雨刷器的摆动效果。
阅读全文