JavaFX围绕其角旋转矩形
我刚开始使用JavaFX,有一个问题。在我的项目中,我想使用旋转矩形。但是矩形只围绕其中心旋转,我希望它围绕其左上角旋转 如图所示(来源): 下面是一些类似于我的项目中的代码:JavaFX围绕其角旋转矩形,java,javafx,rotation,Java,Javafx,Rotation,我刚开始使用JavaFX,有一个问题。在我的项目中,我想使用旋转矩形。但是矩形只围绕其中心旋转,我希望它围绕其左上角旋转 如图所示(来源): 下面是一些类似于我的项目中的代码: import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.K
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.*;
public class Main extends Application {
@Override
public void start(Stage stage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root, 500, 500);
//create rectangle
Rectangle rect = new Rectangle(10, 10, 200, 15);
rect.setTranslateX(250);
rect.setTranslateY(250);
rect.setFill(Color.BLACK);
root.getChildren().add(rect);
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
stage.getScene().setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.LEFT) {
rect.setRotate(rect.getRotate()-5); //<-- rotate rectangle here
} else if (e.getCode() == KeyCode.RIGHT){
rect.setRotate(rect.getRotate()+5); //<-- rotate rectangle here
}
});
}
};
timer.start();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
导入javafx.animation.AnimationTimer;
导入javafx.application.application;
导入javafx.scene.Group;
导入javafx.scene.scene;
导入javafx.scene.input.KeyCode;
导入javafx.scene.paint.Color;
导入javafx.stage.stage;
导入javafx.scene.shape.Rectangle;
导入java.awt.*;
导入java.awt.event.KeyEvent;
导入java.util.*;
公共类主扩展应用程序{
@凌驾
public void start(Stage)引发异常{
组根=新组();
场景=新场景(根,500500);
//创建矩形
矩形rect=新矩形(10,10,200,15);
直译setTranslateX(250);
直译直译(250);
矩形设置填充(颜色为黑色);
root.getChildren().add(rect);
AnimationTimer=新的AnimationTimer(){
@凌驾
公共无效句柄(长){
stage.getScene().setOnKeyPressed(e->{
if(e.getCode()==KeyCode.LEFT){
rect.setRotate(rect.getRotate()-5);//您需要专门使用Transform
和Rotate
来围绕自定义轴旋转节点
//Create a Rotate Object
Rotate rotate = new Rotate();
rotate.setPivotX(node.getX()); //Pivot X Top-Left corner
rotate.setPivotY(node.getY()); //Pivot Y
rotate.setAngle(angle); //Angle degrees
//Add the transform to the node
node.getTransforms().add(rotate);
在代码中
final Rotate rotate = new Rotate();
rect.getTransforms().add(rotate);
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
stage.getScene().setOnKeyPressed(e -> {
rotate.setPivotX(rect.getX());
rotate.setPivotY(rect.getY());
if (e.getCode() == KeyCode.LEFT) {
rotate.setAngle(rotate.getAngle() - 5);
} else if (e.getCode() == KeyCode.RIGHT){
rotate.setAngle(rotate.getAngle() + 5);
}
});
}
};