实现布尔值包含Shape接口的(Rectangle2D r)方法

这是我的Java问题:

我的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????
}
}

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

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

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


使用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
}

鉴于您目前的实施情况:

    public boolean contains(Rectangle2D r)
{
    return this.contains(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
链接地址: http://www.djcxy.com/p/83245.html

上一篇: Implementing boolean contains(Rectangle2D r) method of Shape interface

下一篇: Java Point, difference between getX() and point.x