实现boolean包含Shape接口的(Rectangle2D r)方法

时间:2012-04-24 14:51:24

标签: java interface implementation contains shape

这是我的Java问题:

My Circle类实现了Shape接口,因此它必须实现所需的所有方法。我有一个问题,方法boolean contains(Rectangle2D r)“测试Shape的内部是否完全包含指定的Rectangle2D”。现在,Rectangle2D是一个抽象类,它不提供(尽我所知)任何方法来获取矩形角的坐标。更确切地说:“Rectangle2D类描述了由位置(x,y)和维度(wxh)定义的矩形。这个类只是存储2D矩形的所有对象的抽象超类。坐标的实际存储表示留给子类“。

那我怎么解决这个问题呢?

请在下面找到我的代码的一部分:

public class Circle implements Shape
{
private double x, y, radius;

public Circle(double x, double y, double radius)
{
    this.x = x;
    this.y = y;
    this.radius = radius;
}

// Tests if the specified coordinates are inside the boundary of the Shape
public boolean contains(double x, double y)
{
    if (Math.pow(this.x-x, 2)+Math.pow(this.y-y, 2) < Math.pow(radius, 2))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if the interior of the Shape entirely contains the specified rectangular area
public boolean contains(double x, double y, double w, double h)
{
    if (this.contains(x, y) && this.contains(x+w, y) && this.contains(x+w, y+h) && this.contains(x, y+h))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if a specified Point2D is inside the boundary of the Shape
public boolean contains(Point2D p)
{
    if (this.contains(p.getX(), p.getY()))
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Tests if the interior of the Shape entirely contains the specified Rectangle2D
public boolean contains(Rectangle2D r)
{
    // WHAT DO I DO HERE????
}
}

4 个答案:

答案 0 :(得分:4)

Rectangle2DgetMaxX, getMaxY, getMinX, getMinY继承RectangularShape。所以你可以得到角落的坐标。

http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/geom/Rectangle2D.html

请参阅“从类java.awt.geom.RectangularShape继承的方法”。

答案 1 :(得分:1)

使用PathIterator。适用于所有凸形

PathIterator it = rectangle.getPathIterator(null);
while(!it.isDone()) {
    double[] coords = new double[2];
    it.currentSegment(coords);
    // At this point, coords contains the coordinates of one of the vertices. This is where you should check to make sure the vertex is inside your circle
    it.next(); // go to the next point
}

答案 2 :(得分:0)

鉴于您目前的实施情况:

    public boolean contains(Rectangle2D r)
{
    return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}

答案 3 :(得分:0)

您可以将Ellipse2D.Double扩展为将宽度和高度设置为相同的值。

Ellipse2D.Double(double x, double y, double w, double h)

然后你可以使用它的contains方法传递Rectangle2D角(你有左上角X和Y以及宽度和高度,所以计算角是微不足道的)。 true返回的contains已应用于所有矩形角,表示该圆圈包含矩形