2013 年快乐。
我对 2 个矩形的交集方法有点问题,但我遇到了一个问题,即它不允许我在这个主题上前进。
我正在使用 4 个对象、2 个点和 2 个矩形。Point1 是 rectangle1 的原点,point2 是 rectangle2 的原点。
然后我调用 rectangle1 的 intersect 方法并发送 rectangle2 对象以查看是否有交集。
这里的问题是,在方法内部,两个矩形的原点最终是相同的坐标,因此,如果我没有不同的原点,我将无法获得好的信息。
这是我的 .h 文件:
@interface XYPoint : NSObject
@property int x,y;
-(void) setX:(int)xVal andY: (int) yVal;
@end
@interface Rectangle: graphicObject
@property float width, height;
- (void) setWidth:(float)w andHeight: (float) h;
- (void) setOrigin: (XYPoint *) pt;
- (bool) containsPoint: (XYPoint *) aPoint;
- (void) intersect: (Rectangle *) rect;
@end
这是我的 .m 文件:
@implementation XYPoint
@synthesize x,y;
-(void) setX:(int)xVal andY:(int)yVal;
{
x = xVal;
y = yVal;
}
@end
@implementation Rectangle
@synthesize width, height;
XYPoint *origin;
- (void) setWidth:(float) w andHeight: (float) h;
{
width = w;
height = h;
}
- (float) area
{
return width * height;
}
- (float) perimeter
{
return (2*width) + (2*height);
}
-(void) setOrigin: (XYPoint *) pt
{
if (! origin)
{
origin = [[XYPoint alloc]init];
}
origin.x = pt.x;
origin.y = pt.y;
}
- (XYPoint *) origin
{
return origin;
}
-(void) intersect: (Rectangle *) rect //
{
int pointCount;
pointCount = 0;
/* R1o R2o R1F R2F */
/* origin.x rect.origin.x origin.x+w rect.origin.x+w */
if ( (origin.x <= rect.origin.x) && (rect.origin.x <= (origin.x + width) ) )
pointCount = pointCount +1;
NSLog(@"width = %g height = %g origin = (%d,%d)", width, height, origin.x, origin.y);
NSLog(@"rect.width = %g rect.height = %g rect.origin (%d,%d)", rect.width, rect.height, rect.origin.x, rect.origin.y);
if ( (rect.origin.x <= ( origin.x + width ) ) && (origin.x + width <= rect.origin.x + rect.width) )
pointCount = pointCount + 1;
if ( (origin.y <= rect.origin.y) && (rect.origin.y <= (origin.y + height) ) )
pointCount = pointCount + 1;
if ( (rect.origin.y <= (origin.y + height) && ( origin.y + height <= rect.origin.y + rect.height)) )
pointCount = pointCount +1;
if (pointCount == 4)
NSLog (@"the rectangles intersect!");
else
NSLog (@"The rectangles don't intersect.");
}
@end
这是我的主文件:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Rectangle * myRectangle1 = [[Rectangle alloc] init];
XYPoint * myPoint1 = [[XYPoint alloc]init];
[myPoint1 setX: 0 andY: 0];
[myRectangle1 setWidth: 3 andHeight: 3];
[myRectangle1 setOrigin : myPoint1];
Rectangle * myRectangle2 = [[Rectangle alloc] init];
XYPoint * myPoint2 = [[XYPoint alloc]init];
[myPoint2 setX: 2 andY: 2];
[myRectangle2 setWidth: 4 andHeight: 4];
[myRectangle2 setOrigin : myPoint2];
[myRectangle1 intersect: myRectangle2];
}
return 0;
}
我上次运行它时,我得到了这个:
宽度 = 3 高度 = 3 原点 = (2,2)
rect.width = 4 rect.height = 4 rect.origin (2,2)
矩形相交!
看?两个矩形具有相同的原点,即使它们的设置不同。
非常感谢!