Youngrok Lim Youngrok Lim - 1 year ago 156
Java Question

Algorithm to verify if a shape is inside another - javafx

I have a rectangular and circle. I need to verify whether a rectangle is inside that circle.

I tried to Shape.intersects but intersects is checked the number 1.

Does anyone know this kind of algorithm in javafx?

Just to exemplifly, in the figure only rectangles 1, 2, 3, and 4 are inside the circle.

thanks for your help.

enter image description here

Answer Source

Try this :

import javafx.geometry.Point2D;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;

 Check if a rectangle is contained with in a circle by checking 
 all rectangle corners.
 For the rectangle to be contained in a circle, all its corners should be
 in a distance smaller or equal to the circle's radius, from the circle's center. 
 Requires some more testing. I tested only a few test cases.
 I am not familiar with javafx. This solution does not take into 
 calculation rectangle's arc or other attributes I may not be aware of.
public class Test{

    public static void main(String[] args){

        Circle circle = new Circle(0 ,0, 100);
        Rectangle rec = new Rectangle(0, 0, 50 , 50);

        System.out.println("Is rectungle inside the circle ? "
                                     + isContained(circle,rec));

    //check if rectangle is contained within a circle
    private static boolean isContained(Circle circle,Rectangle rec) {

        boolean isInside = true;

        //get circle center & radius
        Point2D center = new Point2D(circle.getCenterX(), circle.getCenterY());
        double radius= circle.getRadius();

        Point2D[] corners = getRectangleCorners(rec);

        for(Point2D corner : corners) {

            //if any corner falls outside the circle
            //the rectangle is not contained in the circle
            if(distanceBetween2Points(corner, center) > radius) {
                return false;
        return isInside;

    //calculate distance between two points
    //(updated a per fabian's suggestion)
    private static double distanceBetween2Points
                            (Point2D corner, Point2D center) {
        return corner.distance(center);

    private static Point2D[] getRectangleCorners(Rectangle rec) {

        Point2D[] corners = new Point2D[4];
        corners[0] = new Point2D(rec.getX(),                  rec.getY());
        corners[1] = new Point2D(rec.getX()+ rec.getWidth() , rec.getY());
        corners[2] = new Point2D(rec.getX()+ rec.getWidth(),  rec.getY()+ rec.getHeight());
        corners[3] = new Point2D(rec.getX(),                  rec.getY()+ rec.getHeight());

        return corners;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download