4

サークルに長方形が完全に含まれているかどうかを確認するにはどうすればよいですか(Javaの場合)。

public class Circle {
   //x and y define the top left corner of the square bounding this circle
   public int x, y, radius;
}

public class Rectangle {
   //x and y define the top left corner
   public int x, y, width, height;
}

public boolean circleContainsRectangle(Circle circle, Rectangle rect) {
   ...
}
4

4 に答える 4

8

以下は、左下隅にあるcartesian軸の答えです。(0, 0)

編集 あなたx, yは正方形の左上隅なので。それらを中央に変換します。

x = x+r
y = y-r

円の方程式はですx^2 + y^2 = r^2。これで、与えられた点{x, y}は、iffのときに円内または円上になりx^ + y^2 <= r^2ます。これで、四つんばいのコーナーポイントがすべて円内または円上にある場合、長方形が円内にあると安全に仮定できます。長方形が円に含まれているかどうかを見つけるために上記の仮定の擬似コードを使用する:

boolean contains(Circle c) {
    Point p_rect_1 = {x, y};
    Point p_rect_2 = {x + width, y };
    Point p_rect_3 = {x + width, y + height };
    Point p_rect_4 = {x, y + height };
    Point[] points = new Point[] { p_rect_1, p_rect_2, p_rect_3, p_rect_4 };

    foreach(Point p : points) {
        // ** is raise to power
        if ((c.x - p.x)**2 + (c.y - p.y)**2 > c.r**2) {
            return false;
        }
    }
    return true;
}

編集 計算のためのより最適化されたアプローチ(以下のコメントでジムによって提案された)は、円の中心から長方形の最も遠い角を計算することによるでしょう:

dx = max(centerX - rectLeft, rectRight - centerX); 
dy = max(centerY - rectTop, rectBottom - centerY);
return radius*radius >= dx*dx + dy*dy
于 2012-12-31T04:16:47.200 に答える
3

おそらく最も簡単な方法は、長方形の4つの角すべてが円の中心から単位未満radius離れているかどうかを確認することです。そうである場合、長方形内のすべての点は円の内側にあります。チェックする必要がある4つのポイントは、(x、y)、(x +幅、y)、(x、y +高さ)、および(x +幅、y +高さ)です。

注:円が右上隅から定義され、長方形が左上隅から定義されるのは奇妙です。円の中心を計算するときは、それを考慮に入れてください。

于 2012-12-31T04:08:25.470 に答える
0

スウィフト4:

func checkCircleContainsRect(circle: Circle, rect: CGRect) -> Bool
    {
        let dx = max(abs(circle.position.x - rect.minX), abs(rect.maxX - circle.position.x))
        let dy = max(abs(circle.position.y - rect.maxY), abs(rect.minY - circle.position.y))
        return (circle.radius * circle.radius) >= (dx * dx) + (dy * dy)
    }
于 2018-01-03T18:33:50.207 に答える
-1

私は遅れていることを知っていますが、私の考えを共有したいと思いました。何か問題がある場合は。私はちょうどwidth/2とheight/2を使用して、高さの半分と幅の半分を定義しました。次に、ピタゴラス定理を使用して中心から角までの距離を計算し、半径よりも大きいかどうかを確認しました。私はそのjavaを知っています、しかし私はそれにコーディングすることができません、しかし私はc++で同じプログラムを作りたいです。とにかくここにコードがあります:

#include <iostream>
#include <math.h>

using namespace std;

void rectangle_in_circle(float w, float h,float r){
    //sides of square triangle
    float a;
    float b;
    float c;
    //pythagorean theorem
    b = h/2;
    a = w/2;
    c = sqrt(pow(b,2) + pow(a,2));
    //output
    if(c <= r){
        cout << "true" << endl;
    }else{
        cout << "false" << endl;
    }
    }

int main(){ 

    rectangle_in_circle(4,7,5);
    return 0;
}
于 2020-11-26T07:13:36.503 に答える