2024年12月10日 星期二

Two ways to draw shapes in JavaFX

 JavaFX 有 2 種畫形狀的寫法如下:

A. Pane容器放 Shape 形狀

import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;

....

        Pane pane = new Pane();

        Circle circle = new Circle(50, 50, 30);
        circle.setFill(Color.BLUE);

        Rectangle rectangle = new Rectangle(100, 100, 80, 40);
        rectangle.setFill(Color.RED);

        pane.getChildren().addAll(circle, rectangle);

註1: Pane小孩清單會記住所有加入形狀元件,Pane大小調整後也會重新顯示所有形狀
註2: javafx.scene.shape支援形狀有
         Circle, Rectangle, Ellipse, Line, Polygon, Polyline, 
         Arc, CubicCurve, QuadCurve, Path 等

B. Canvas元件上畫出形狀

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

.....

        Canvas canvas = new Canvas(300, 200);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        gc.setFill(Color.BLUE);
        gc.fillOval(50, 50, 60, 60); // Draw a circle

        gc.setFill(Color.RED);
        gc.fillRect(150, 100, 80, 40); // Draw a rectangle

        
註1: javafx.scene.canvas.GraphicsContext會暫時記住所有畫圖區內容,直到大小異動才清空
註2: javafx.scene.canvas.GraphicsContext支援形狀有

// 矩形
 fillRect(double x, double y, double w, double h) // 前景色填滿
 strokeRect(double x, double y, double w, double h) // 前景色畫框
 clearRect(double x, double y, double w, double h)  // 背景色填滿

// 圓形
 fillOval(double x, double y, double w, double h)
 strokeOval(double x, double y, double w, double h)

// 弧形
 fillArc(double x, double y, double w, double h, 
         double startAngle, double arcExtent, ArcType closure)
 strokeArc(double x, double y, double w, double h, 
           double startAngle, double arcExtent, ArcType closure)

// 多邊形,多邊線
 fillPolygon(double[] xPoints, double[] yPoints, int nPoints)
 strokePolygon(double[] xPoints, double[] yPoints, int nPoints)
 fillPolyline(double[] xPoints, double[] yPoints, int nPoints)
 strokePolyline(double[] xPoints, double[] yPoints, int nPoints)
 strokeLine(double x1, double y1, double x2, double y2)

// 路徑模式, 一次只能維護一條路徑
 beginPath()
 moveTo(double x, double y)
 lineTo(double x, double y)
 closePath()
 stroke()  // 畫路徑框
 fill() // 畫路徑內部

沒有留言: