如何在 JavaFX 中繪製幾何圖形?


一般來說,2D 形狀是可以在 XY 平面繪製的幾何圖形,包括直線、矩形、圓形等等。

javafx.scene.shape 包提供了各種類,每個類都表示/定義了一個 2d 幾何物件或對它們的某個運算。名為 Shape 的類是 JavaFX 中所有二維形狀的基類。

建立 2D 形狀

要使用 JavaFX 繪製 2D 幾何圖形,你需要 −

  • 例項化類 − 例項化相應的類。例如,如果你想繪製一個圓形,你需要例項化 Circle 類,如下所示 −

//Drawing a Circle
Circle circle = new Circle();
  • 設定屬性 − 使用相應類的函式設定形狀的屬性。例如,要繪製一個圓形,你需要中心點和半徑,並分別使用 setCenterX()、setCenterY() 和 setRadius() 函式設定這些屬性。

//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
circle.setRadius(100.0f);
  • 將形狀物件新增到組 − 最後,將建立的形狀作為一個引數傳遞給組建構函式,如下 −

Group root = new Group(circle);

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class CircleExample extends Application {
   public void start(Stage stage) {
      //Drawing a Circle
      Circle circle = new Circle();
      //Setting the properties of the circle
      circle.setCenterX(300.0f);
      circle.setCenterY(135.0f);
      circle.setRadius(100.0f);
      //Creating a Group object
      Group root = new Group(circle);
      //Creating a scene object
      Scene scene = new Scene(root, 600, 300);
      //Setting title to the Stage
      stage.setTitle("Drawing a Circle");
      //Adding scene to the stage
      stage.setScene(scene);
      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 2020 年 4 月 13 日

236 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.