Opération d'intersection de formes 2D (objets)

Cette opération prend deux formes ou plus comme entrées et renvoie la zone d'intersection entre elles, comme illustré ci-dessous.

Vous pouvez effectuer une opération d'intersection sur les formes à l'aide de la méthode nommée intersect(). Puisqu'il s'agit d'une méthode statique, vous devez l'appeler en utilisant le nom de la classe (Shape ou ses sous-classes) comme indiqué ci-dessous.

Shape shape = Shape.intersect(circle1, circle2);

Voici un exemple de l'opération d'intersection. Ici, nous dessinons deux cercles et effectuons une opération d'intersection sur eux.

Enregistrez ce code dans un fichier avec le nom IntersectionExample.java

Exemple

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

Compilez et exécutez le fichier java enregistré à partir de l'invite de commande à l'aide des commandes suivantes.

javac IntersectionExample.java 
java IntersectionExample

Lors de l'exécution, le programme ci-dessus génère une fenêtre JavaFX affichant la sortie suivante -