JavaFX Intersect(교차) 연산이란?
교차(Intersect) 연산은 두 개 이상의 도형을 입력으로 받아, 도형들이 서로 겹치는 공통 영역을 결과로 반환합니다. 아래 그림처럼 여러 개의 원이 겹쳐 있을 때, 세 도형 모두에 포함되는 중앙 부분만 추출해 낼 수 있습니다.

javafx.scene.shape.Shape 클래스가 제공하는 정적(static) 메서드인 intersect()는 두 개의 Shape 객체를 인자로 받아, 두 도형에 대한 교차 연산 결과를 새로운 Shape 객체로 반환합니다. 참고로 같은 클래스에는 합집합을 구하는 union(), 차집합을 구하는 subtract() 메서드도 함께 제공되므로, 상황에 맞게 활용하면 다양한 도형 조합을 손쉽게 만들 수 있습니다.
예제 코드
다음 예제에서는 세 개의 원을 생성한 뒤, intersect() 메서드를 두 번 호출하여 세 원이 모두 겹치는 영역을 구하고 이를 빨간색으로 채워 화면에 출력합니다.
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 JavaFXIntersectExample extends Application {
public void start(Stage stage) {
// 첫 번째 원 그리기
Circle circle1 = new Circle();
circle1.setCenterX(230.0f);
circle1.setCenterY(100.0f);
circle1.setRadius(75.0f);
circle1.setFill(Color.DARKRED);
// 두 번째 원 그리기
Circle circle2 = new Circle();
circle2.setCenterX(280.0f);
circle2.setCenterY(170.0f);
circle2.setRadius(75.0f);
circle2.setFill(Color.DARKRED);
// 세 번째 원 그리기
Circle circle3 = new Circle();
circle3.setCenterX(330.0f);
circle3.setCenterY(100.0f);
circle3.setRadius(75.0f);
circle3.setFill(Color.DARKRED);
// 교차(Intersect) 연산 수행
Shape intersect = Shape.intersect(circle1, circle2);
intersect = Shape.intersect(intersect, circle3);
intersect.setFill(Color.RED);
// 스테이지 설정
Group root = new Group(circle1, circle2, circle3, intersect);
Scene scene = new Scene(root, 595, 300);
stage.setTitle("Intersect Operation");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
실행 결과
프로그램을 실행하면 아래와 같이 세 개의 원이 모두 겹치는 중앙 영역만 붉은색으로 표시되는 것을 확인할 수 있습니다. 이처럼 intersect() 메서드를 연속으로 호출하면 세 개 이상의 도형에 대한 교차 영역도 간단하게 계산할 수 있습니다.
