2017-03-03 55 views
1

我試圖圍繞它的中心旋轉一個矩形。使用GraphicsContext即gc將旋轉繪製到畫布上。這是我的繪圖代碼。JavaFX旋轉矩形關於中心?

gc.save();  
gc.translate(center.x, center.y); 
gc.rotate(this.angle); 
gc.strokeRect(0,0, this.width, this.height); 
gc.restore(); 

這將矩形移動到其中心,然後圍繞它的左上角旋轉矩形。我試着減去兩邊的長度和寬度的一半,但這只是讓它飛到了這個地方。我吮吸數學,也許有人在這裏更好,可以告訴我我做錯了什麼。

如果需要該信息,我還存儲了矩形的所有四個點(角點)。

謝謝, 喬

回答

1

圍繞指定的點的旋轉需要由來自翻譯原點周圍的轉換和旋轉如下:

  1. 使用平移旋轉的中心移到起源。
  2. 繞原點
  3. 使用逆向翻譯的第一翻譯

第三部分是從你的代碼失蹤。

@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(); 
} 

您也可以簡單地用一個Rotate與指定的樞軸來實現所期望的效果:

@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(); 
} 
+0

gc.transform(新仿射(新旋轉( 45,rotationCenterX,rotationCenterY)));這解決了一切。 –