Java: Thao tác Intersection
Thao tác Intersection lấy hai hoặc nhiều hình dạng làm đầu vào và trả về vùng giao nhau giữa chúng như hình dưới đây.
Bạn có thể thực hiện thao tác giao nhau trên các hình dạng bằng phương thức có tên là intersect(). Vì đây là một phương thức tĩnh, bạn nên gọi nó bằng tên lớp (Hình dạng hoặc các lớp con của nó) như hình dưới đây.
Shape shape = Shape.intersect(circle1, circle2);
Sau đây là một ví dụ về hoạt động giao cắt. Ở đây, chúng tôi đang vẽ hai vòng tròn và thực hiện thao tác giao nhau trên chúng.
Lưu mã này trong một tệp có tên IntersectionExample.java
Thí dụ
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; public class IntersectionExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle1 = new Circle(); //Setting the position of the circle circle1.setCenterX(250.0f); circle1.setCenterY(135.0f); //Setting the radius of the circle circle1.setRadius(100.0f); //Setting the color of the circle circle1.setFill(Color.DARKSLATEBLUE); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(350.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.BLUE); //Performing intersection operation on the circle Shape shape = Shape.intersect(circle1, circle2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Intersection Example"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } }
Biên dịch và thực thi tệp java đã lưu từ dấu nhắc lệnh bằng các lệnh sau.
javac IntersectionExample.java java IntersectionExample
Khi thực thi, chương trình trên tạo một cửa sổ JavaFX hiển thị kết quả sau: