簡體   English   中英

兩個矩形的C ++交集

[英]C++ intersection of two rectangles

我在弄清楚程序的這一部分時遇到了問題:

編寫一個具有兩個Rectangle參數的非成員函數交集(),並返回一個包含兩個交集的Rectangle。 當然,如果兩個矩形不相交,則應返回默認的矩形。

到目前為止,這是我的.cpp代碼:

Rectangle::Rectangle()
{
    p1.x = 0;
    p1.y = 0;
    p2.x = 0;
    p2.y = 0;
}
Rectangle::Rectangle(double x, double y, double width, double height)
{
    p1.x = x;
    p1.y = y;
    p2.x = x + width;
    p2.y = y + height;
}
double Rectangle::getArea() const
{
    return (p2.x - p1.x) * (p2.y - p1.y);
}
double Rectangle::getWidth() const
{
    return (p2.x - p1.x);
}
double Rectangle::getHeight() const
{
    return (p2.y - p1.y);
}
double Rectangle::getX() const
{
    return p1.x;
}
double Rectangle::getY() const
{
    return p1.y;
}
void Rectangle::setLocation(double x, double y)
{
    p1.x = x;
    p1.y = y;
}
void Rectangle::setSize(double width, double height)
{
    p2.x = width;
    p2.y = height;
}

Rectangle intersection(const Rectangle& rec1, const Rectangle& rec2)
{
    double ix = 0.0;
    double iy = 0.0;
    double iwidth = 0.0;
    double iheight = 0.0;

    if(rec1.getX() > rec2.getX() && rec2.getX() > (rec1.getX() + rec1.getWidth()) 
        && rec1.getY() > rec2.getY() && rec2.getY() > (rec1.getY() + rec1.getHeight()))
    {
        ix = rec2.getX();
        iy = rec2.getY();
        iwidth = rec1.getX() + rec1.getWidth();
        iheight = rec1.getY() + rec1.getHeight();
    }

我沒有寫“ else”部分,因為首先,此“ if語句在某些情況下應檢查正確,但不正確;我假設(0,0)在左下角,因為我已經嘗試過了” (0,0)位於左上角並且不起作用

將矩形的交點視為2對間隔的交點:

第一對是矩形水平邊的交點:

交集1 = (rec1.getX(), rec1.getX()+rec1.getWidth())(rec2.getX(), rec2.getX()+rec2.getWidth())

第二對是矩形的垂直邊的交點:

交點2 = (rec1.getY(), rec1.getY()+rec1.getHeight())(rec2.getY(), rec2.getY()+rec2.getHeight())

如果這兩個交點都不為空,則可以使結果交點矩形的邊為這些交點。

您需要做的就是正確實現區間交點功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM