Chr*_*ama 4 javafx center rotation rectangles
我正在尝试围绕其中心旋转一个矩形。使用 GraphicsContext 即 gc 将旋转绘制到画布上。这是我的绘图代码。
gc.save();
gc.translate(center.x, center.y);
gc.rotate(this.angle);
gc.strokeRect(0,0, this.width, this.height);
gc.restore();
Run Code Online (Sandbox Code Playgroud)
这会将矩形移动到其中心,但随后会围绕其左上角点旋转矩形。我尝试减去侧面长度和宽度的一半,但这只会让它飞得到处都是。我数学很差,也许这里有更好的人可以告诉我我做错了什么。
如果需要该信息,我还存储了矩形的所有四个点(角)。
谢谢,乔
围绕指定点的旋转需要由平移变换和围绕原点的旋转组成,如下所示:
您的代码中缺少第三部分。
例子
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(400, 400);
double x = 50;
double y = 100;
double width = 100;
double height = 200;
GraphicsContext gc = canvas.getGraphicsContext2D();
double rotationCenterX = (x + width) / 2;
double rotationCenterY = (y + height) / 2;
gc.save();
gc.translate(rotationCenterX, rotationCenterY);
gc.rotate(45);
gc.translate(-rotationCenterX, -rotationCenterY);
gc.fillRect(0, 0, width, height);
gc.restore();
Scene scene = new Scene(new Group(canvas));
primaryStage.setScene(scene);
primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)
您还可以简单地使用Rotate带有指定枢轴的 a 来达到所需的效果:
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(400, 400);
double x = 50;
double y = 100;
double width = 100;
double height = 200;
GraphicsContext gc = canvas.getGraphicsContext2D();
double rotationCenterX = (x + width) / 2;
double rotationCenterY = (y + height) / 2;
gc.save();
gc.transform(new Affine(new Rotate(45, rotationCenterX, rotationCenterY)));
gc.fillRect(0, 0, width, height);
gc.restore();
Scene scene = new Scene(new Group(canvas));
primaryStage.setScene(scene);
primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10886 次 |
| 最近记录: |